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

从数据库获取数据有问题。 我正在尽力解释这个问题。

1.如果我在下面的代码里面留下“模式”:“no-cors”,那么我可以用邮递员从服务器取回数据,但是不能从我自己的服务器上取回数据。 认为它必须是我的客户端错误

  1. 当我删除“模式”:“no-cors”,那么我得到2错误: – 获取API无法加载http:// localhost:3000 / 。 在预检响应中,访问控制允许标题不允许请求标头字段访问控制允许来源。 -Uncaught(在promise中)TypeError:无法获取

“快速浏览”build议将“模式”设置为:“解决这个错误”的“非Cors”,但是这并不是一件正确的事情。

所以我想也许有人build议如何解决这个问题。

真的很希望我很清楚,但是我很确定这里没有给出明确的解释:S

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

添加mode:'no-cors'请求头中的mode:'no-cors'保证响应中没有响应

添加一个“非标准”头文件,行'access-control-allow-origin'会触发一个OPTIONS预检请求,你的服务器必须正确处理这个请求才能发送POST请求

你也正在做错误… fetch返回一个“承诺”的Response对象,承诺创build者的jsontext等,这取决于内容types…

简而言之,如果你的服务器端正确地处理CORS(从你的评论中可以看出它确实如此),下面的内容应该可以工作

 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感兴趣(它把所有对象都串联起来),所以做起来更简单

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