【发布时间】:2021-11-07 18:01:40
【问题描述】:
它搜索并已经包含了典型的后端代码
app.use(function (req, res, next) {
//res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000/storeScore');
res.header('Access-Control-Allow-Origin', '*');
//res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
但我仍然得到Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/storeScore. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).,然后是
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. 我的意思是我没有标题res.header('Access-Control-Allow-Origin', '*'); 吗?
我的前端代码是
function someFunction() {
const sessionHighscore = cumulativeScore;
const options = {
method: 'POST',
headers: {
//'Origin' : 'http://localhost:80',
'Content-Type': 'application/json'
},
body: JSON.stringify(sessionHighscore)
};
fetch('http://localhost:3000/storeScore', options);
}
也许我需要在客户端标头中包含一些内容?我认为本地 html 托管在端口 80 上?
注意事项:
- 我正在尝试将数据从本地网站发送到 localhost:3000 上的 mysql 数据库
- 我正在使用 express 作为后端,并尝试不使用 cors 模块作为解决方案
- 还有什么资源可以告诉我如何在不手动更改的情况下执行路由 本地主机?喜欢使用 localHost:3000/createTable 我必须在 url 中手动输入这个,我可以用代码来做吗?
编辑:
- 查看浏览器中的网络选项卡,我发现 OPTIONS 请求成功,但之后的 POST 缺少“Access-Control-Allow-Origin”标头;我只需要知道如何确保 POST 也获取标题
【问题讨论】:
-
它显示“CORS 标头‘Access-Control-Allow-Origin’缺失”,这表明后端代码设置错误。
-
但
res.header('Access-Control-Allow-Origin', '*');确实存在,所以您认为后端有什么问题?
标签: javascript node.js express cors localhost