首页 > 解决方案 > 使用 CORS 策略的 Sails、React 和 Axios 错误:请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述

我真的研究过这个问题,但 SailsJS 还不清楚。我正在运行并使用 npm start 在本地做出反应。

版本:

错误: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.

我真的检查了 stackoverflow.com 中的票和sails 中的文档,还测试了不同的解决方案和选项,我可以使用的唯一方法是使用Moesif Origin & CORS Changerchrome 中的小部件,但我需要配置标题和产品的安全性:

https://sailsjs.com/documentation/concepts/security/cors,https://sailsjs.com/documentation/reference/configuration/sails-config-security _ _

请求标头:

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 的配置是:

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
};

React 中的 Axios 请求:

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);
});

和路由请求:

  'GET /User/Read/:id': {
    controller: "User", 
    action: "read"
  },

标签: node.jsreactjsaxioscorssails.js

解决方案


我只是这样使用

cors: {
    allRoutes: true,
    allowOrigins: "*",
    allowCredentials: false,
    allowRequestHeaders: "*",
  }

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


推荐阅读