gpt4 book ai didi

javascript - 未捕获( promise 中)TypeError : Failed to fetch and Cors error

转载 作者:IT老高 更新时间:2023-10-28 22:12:36 25 4
gpt4 key购买 nike

从数据库取回数据时遇到问题。我正在尽力解释问题。

1.如果我在下面的代码中保留“mode”:“no-cors”,那么我可以使用 Postman 从服务器获取数据,但不能从我自己的服务器获取数据。认为它必须是我的客户端错误

  1. 当我删除 "mode":"no-cors"时,我收到 2 个错误:-Fetch API 无法加载 http://localhost:3000/ . Access-Control-Allow-Headers 在预检响应中不允许请求 header 字段 access-control-allow-origin。-Uncaught (in promise) TypeError: Failed to fetch

Quick Browsing 建议输入 "mode":"no-cors"来修复此错误,但感觉不妥。

所以我想也许有人对如何解决这个问题提出了建议。

真的希望我足够清楚,但我很确定我在这里没有给出明确的解释: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'到请求头保证响应中没有可用的响应

添加“非标准”标题,行 'access-control-allow-origin'将触发一个 OPTIONS 预检请求,您的服务器必须正确处理该请求才能发送 POST 请求

你也在做fetch错了... fetch返回 Response 的“ promise ”具有 json 的 promise 创建者的对象, text等,具体取决于内容类型...

简而言之,如果您的服务器端正确处理 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;
});
}

关于javascript - 未捕获( promise 中)TypeError : Failed to fetch and Cors error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42754388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com