Uncaught ...TypeError:Failedtofetch and Corserror如何解决?

我从数据库取回数据时遇到这个问题,我尽量详细的解释一下。

  1. 如果我在下面的代码中保留“mode”:“no-cors”,那么我可以用 Postman 从服务器获取数据,但不能从我自己的服务器获取数据。我想这是由于我的客户端错误
  2. 当我删除 “mode”:“no-cors” 时,我收到 2 个错误:

    • Fetch API cannot load http://localhost:3000/. Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
    • Uncaught (in promise) TypeError: Failed to fetch

    快速浏览建议输入 “mode”:“no-cors” 以修复此错误,但感觉不正确。
    所以我想也许有人建议如何解决这个问题。

    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);
     });
    }
    
原文由 OFFLlNE 发布,翻译遵循 CC BY-SA 4.0 许可协议
阅读 3.3k
2 个回答

在请求头中添加 mode:'no-cors' 在请求头中添加mode:'no-cors'可以保证请求成功,但拿不到服务器返回数据

添加 “non standard” 请求头,'access-control-allow-origin' 将触发 OPTIONS 预检请求,服务器必须正确处理该请求才能发送 POST 请求

fetch 这里也写错了... fetchResponse 对象返回一个“promise”,该对象具有 jsontext 等 promise 构造器,具体取决于内容类型...

简而言之,如果你的服务器端正确处理 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;
 });
 }
原文由 Jaromanda X 发布,翻译遵循 CC BY-SA 4.0 许可协议

根据我自己的实践经验,感觉问题出在协议上。我试图用 http 而不是 https 来调用一个 script url 。

原文由 IgniteCoders 发布,翻译遵循 CC BY-SA 4.0 许可协议
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题