【问题标题】:Client-side code to fix CORs issue when using fetch (without cors module)使用 fetch 时修复 COR 问题的客户端代码(没有 cors 模块)
【发布时间】: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


【解决方案1】:

请安装包 npm i cors。

然后将中间件应用为:

要求为

 const cors = require("cors");   

中间件代码

app.use(cors())

【讨论】:

    【解决方案2】:

    在您的获取请求中,添加 useCredentials: true。

    【讨论】:

    • 为什么?他们没有发送任何凭据。
    • 您不应该在包含数据的发布请求上将其设置为 true 吗?我可能是错的。
    • 不,仅适用于带有凭据的请求。
    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2020-03-01
    • 2022-08-23
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2013-04-25
    • 2018-10-26
    相关资源
    最近更新 更多