首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CORS策略进行Sails、React和Axios错误:请求的资源上不存在“访问控制-允许-原产地”标头。

使用CORS策略进行Sails、React和Axios错误:请求的资源上不存在“访问控制-允许-原产地”标头。
EN

Stack Overflow用户
提问于 2020-12-19 04:18:53
回答 4查看 3.3K关注 0票数 0

我真的研究过这个问题,对SailsJS来说什么都不清楚。我正在操纵船帆,在npm启动的地方做出反应。

守护神:

  • Sailsjs: 1.4.0
  • ReactJS:

^0.19.2

  • Node: v15.0.1

错误:Access to XMLHttpRequest at 'http://localhost:1337/User/Read/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我真的检查了船票和船帆中的,还测试了不同的解决方案和选项,唯一的方法是使用小部件使用chrome,但是我需要配置头和prod:的安全性。

https://sailsjs.com/documentation/concepts/security/corshttps://sailsjs.com/documentation/reference/configuration/sails-config-security

请求头:

代码语言:javascript
复制
GET /User/Read/2 HTTP/1.1
Host: localhost:1337
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Origin: http://localhost:3000
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

我在security.js中为风帆中的cors配置的配置是:

代码语言:javascript
复制
module.exports.security = {
  cors: {
    allRoutes: true,
    allowOrigins: ['http://localhost:3000'],
    allowCredentials: false,
    allowRequestHeaders: [
      'X-Powered-By', 
      'Content-Type', 
      'Accept', 
      'Origin',
      'Accept-Encoding',
      'Accept-Language',
      'Connection',
      'Host',
      'Origin',
      'Referer',
      'Sec-Fetch-Dest',
      'Sec-Fetch-Mode',
      'Sec-Fetch-Site',
      'User-Agent',
      'Pragma',
      'Cache-Control',
    ]
  },
  csrf: false
};

Axios要求作出反应:

代码语言:javascript
复制
var axios = require('axios');
axios({
      method: 'get',
      headers: {     
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8'},
      url: 'http://localhost:1337/User/Read/2',
    }).then(function (response) {
      console.log(response.data);
});

而路线要求:

代码语言:javascript
复制
  'GET /User/Read/:id': {
    controller: "User", 
    action: "read"
  },

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-03-12 22:03:45

/config/http.js文件中,取消对“order”数组片段的注释,并在myRequestLogger方法中添加标头参数。

代码语言:javascript
复制
order: [
  'startRequestTimer',
  'cookieParser',
  'session',
  'myRequestLogger',
  'bodyParser',
  'handleBodyParserError',
  'compress',
  'methodOverride',
  'poweredBy',
  '$custom',
  'router',
  'www',
  'favicon',
  '404',
  '500'
],


 myRequestLogger: function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
  res.header('Allow', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
  res.header('X-Powered-By', '');
  return next();
},

/config/cors.js (sailsv0.12)或/config/security.js (sailsv1.x)中添加以下代码片段

代码语言:javascript
复制
module.exports.security = { //sails v1.x, if is sails v0.12 change security for cors
  allRoutes: true,
  allowOrigins: '*',
  allowCredentials: false,
  allowRequestMethods: 'GET,POST,PUT,DELETE,OPTIONS,HEAD',
  allowRequestHeaders: 'content-type'
}

如果所有这些都不起作用(我觉得很难做到),请添加控制器方法的返回(但是,我认为没有必要):

代码语言:javascript
复制
  return res.set({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
  }).json({ status: true, //body });
票数 1
EN

Stack Overflow用户

发布于 2020-12-28 04:26:47

我就像这样用

代码语言:javascript
复制
cors: {
    allRoutes: true,
    allowOrigins: "*",
    allowCredentials: false,
    allowRequestHeaders: "*",
  }

确保在生产时在allowOrigins: ['http://mywebsite.com]中添加客户端主机

票数 2
EN

Stack Overflow用户

发布于 2020-12-21 20:38:11

最后,我用这样的方式解决了这个问题:

在http.js上的sails中,添加了req标题:

代码语言:javascript
复制
module.exports.http = {

  middleware: {
    order: [
      'cookieParser',
      'session',
      'bodyParser',
      'compress',
      'poweredBy',
      'appRequestLogger', // custom logger
      'router',
      'www',
      'favicon'
    ],

    appRequestLogger: function (req, res, next) {
      const env = process.env.NODE_ENV || 'development';
      sails.log.debug('<<------------------------------');
      sails.log.debug('Requested data :: ');
      sails.log.debug('  ', req.method, req.url);
      sails.log.debug('   Headers:');
      sails.log.debug(req.headers);
      if (env.toLowerCase() !== 'production') {
        sails.log.debug('   Params:');
        sails.log.debug(req.params);
        sails.log.debug('   Body:');
        sails.log.debug(req.body);
      }
      sails.log.debug('------------------------------>>');

      // This is a work around to allow CORS requests as Sails does not send these
      // headers in the response to preflight/actual requests even when they are
      // declared in config/security.js under CORS config

        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
        res.header('Allow', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
        res.header('X-Powered-By', '');

      // Check graphql preflight request, if yes then prevent the request reaching
      // the express-graphql server. Currently the express-graphql server only accepts
      // GET and POST hence rejects the preflight request. CORS needs that a server
      // accepts preflight requests to facilitate cross-site access. Therefore, return
      // immediately with a success.
      // Otherwise fall through by calling next()

      if (req.method === 'OPTIONS' && req.url.indexOf('graphql') > -1) {
        return res.status(200).send();
      } else {
        return next();
      }
    },

  },

};

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65366607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档