【问题标题】:how to bypass CORS如何绕过 CORS
【发布时间】:2021-11-04 06:12:54
【问题描述】:

当我尝试将表单数据发布到“http://localhost:3001/”时,我遇到了这个问题。问题是,当我尝试从服务器获取数据时,我遇到了这个有点确切的问题,但是这段代码修复了它。

app.use(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', 'PUT, POST, GET, DELETE, OPTIONS');
    next();
  });

但是从前端或者更确切地说是 POST 表单数据我得到了 CORS 问题。

<form id = "newNote-content" method = "post" encType = "application/x-www-form-urlencoded" action = "http://localhost:3001/api">
... previous code
<button id = "submit" onClick = {checkConnection}><p>Submit</p></button>
</form>
function checkConnection(e){
    e.preventDefault();
    let formData = new FormData();
    let myForm = document.getElementById("newNote-content"); // form
    let method = myForm.method; // form method

    let noteNameInput = document.getElementById("noteName");
    let noteImportant = document.getElementById("checkB-important");
    let noteDateInput = document.getElementById("remindDate");
    let noteMsgInput = document.getElementById("noteMsg");
    //-----------------
    var xhr = new XMLHttpRequest();
    xhr.onload = () =>{
        if (xhr.status === 200){
            formData.append("noteName", noteNameInput.value);
            formData.append("important", noteImportant.value);
            formData.append("reminder", noteDateInput.value);
            formData.append("noteMsg", noteMsgInput.value);
        } else {
            console.log("not ok")
        }
    };

    xhr.open(method, "http://localhost:3001/", true);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xhr.send(formData);
};

我该如何解决这个问题?提前谢谢你。

【问题讨论】:

  • 你不能绕过 CORS - 你可以使用自己的服务器来发出请求 - 但似乎是你的服务器配置错误 - 你应该为 cors 配置你的服务器 - 看起来像是 expressjs -有一个你可以使用的 cors 库
  • " 当我尝试从服务器获取数据时遇到了这个有点确切的问题,但是这段代码修复了它" - 这应该是什么意思?您正在谈论的配置是不是您尝试向现在发出其他请求的系统/组件吗?您收到的实际错误消息是什么?
  • @CBroe,我对此很陌生,如果我回答错误,请见谅。我有一个 json 文件,我尝试在前端通过快速服务器访问该文件。由于cors,它不起作用,我在网上搜索,我得到了解决我问题的代码示例。现在我想通过 exress 服务器将对象(表单数据)发布到 json 文件。但是控制台告诉我 cors 不允许我这样做。我希望我正确地解释了自己。
  • 我向您询问了实际的错误消息,所以请引用它,而不是仅仅给我们 "告诉我 cors 不允许我这样做那个”
  • @Bravo 谢谢我认为你解决了我的问题,cors 警告不再出现。

标签: javascript node.js reactjs express cors


【解决方案1】:

对于本地开发,我使用 https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/ 插件不关心 cors。

【讨论】:

    猜你喜欢
    • 2019-12-23
    • 2019-09-24
    • 2021-10-31
    • 2017-08-31
    • 1970-01-01
    • 2015-08-17
    • 2019-12-14
    • 2023-04-10
    • 2017-05-28
    相关资源
    最近更新 更多