且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

未捕获(承诺)TypeError:无法获取和Cors错误

更新时间:2023-08-25 09:42:16

添加模式:'no-cors'到请求标头保证响应中没有响应

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

添加非标准 header,line 'access-control-allow-origin'将触发OPTIONS预检请求,服务器必须正确处理该请求才能发送POST请求

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

您还在做 fetch 错误... fetch 返回 Response 对象的承诺,该对象具有 json 的承诺创建者, text 等等取决于内容类型......

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

简而言之,如果您的服务器端正确处理CORS(从您的评论中暗示它确实如此) )以下应该工作

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        }
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.json();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
    });
}

但是,因为你的代码对JSON并不感兴趣(它将字符串化毕竟对象) - 它更简单

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        }
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.text();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = muutuja;
    });
}