node.js - 使用 CORS 策略的 Sails、React 和 Axios 错误:请求的资源上不存在“Access-Control-Allow-Origin”标头
问题描述
我真的研究过这个问题,但 SailsJS 还不清楚。我正在运行并使用 npm start 在本地做出反应。
版本:
- Sailsjs:1.4.0
- 反应JS:^16.13.1
- 爱讯:^0.19.2
- 节点: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.
我真的检查了 stackoverflow.com 中的票和sails 中的文档,还测试了不同的解决方案和选项,我可以使用的唯一方法是使用Moesif Origin & CORS Changer
chrome 中的小部件,但我需要配置标题和产品的安全性:
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"
},
解决方案
我只是这样使用
cors: {
allRoutes: true,
allowOrigins: "*",
allowCredentials: false,
allowRequestHeaders: "*",
}
确保allowOrigins: ['http://mywebsite.com]
在生产中添加客户端主机
推荐阅读
- sql - 完全外连接、合并和分组(哦,我的!)
- if-statement - 如何在 COGNOS 中使用 IF 和 CAST 函数?
- django - GeoDjango + PostGIS:纯几何 SRID
- r - dplyr 列联表中的准确比例
- python - Scipy sigmoid 曲线拟合
- c++ - C ++单例继承问题
- drupal - 将旧网站的数据导入具有不同架构的新 drupal 网站
- flutter - 如何使用 Flutter 创建 _showMenu 函数,该函数动态构建弹出菜单并允许处理选定的选项
- wordpress - 如何在WordPress的静态页面中按类别显示帖子
- node.js - 离子文件传输太大?