Uncaught (in promise) TypeError: Failed to fetch and Cors error

前端 未结 4 1056
无人共我
无人共我 2020-11-30 04:05

having a problem with getting data back from database. I am trying my best to explain the problem.

1.If I leave \"mode\":\"no-cors\" inside the code below, then I ca

4条回答
  •  忘掉有多难
    2020-11-30 04:36

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

    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

    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...

    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);
        });
    }
    

    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;
        });
    }
    

提交回复
热议问题