OFF*_*lNE 24 javascript node.js cors
从数据库中获取数据时遇到问题.我正在尽力解释这个问题.
1.如果我在下面的代码中留下"模式":"no-cors",那么我可以使用Postman从服务器获取数据,但不能从我自己的服务器获取数据.认为它必须是我的客户端错误
快速浏览建议放入"模式":"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);
});
}
Run Code Online (Sandbox Code Playgroud)
Jar*_*a X 12
添加mode:'no-cors'到请求标头可确保响应中没有可用的响应
添加"非标准"标题,行将'access-control-allow-origin'触发OPTIONS预检请求,服务器必须正确处理该请求才能发送POST请求
你也做fetch不对...... fetch返回了一个"承诺" Response这对于承诺的创造者对象json,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);
});
}
Run Code Online (Sandbox Code Playgroud)
但是,因为你的代码对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;
});
}
Run Code Online (Sandbox Code Playgroud)
尝试这个
await fetch(url, {
mode: 'no-cors'
})
Run Code Online (Sandbox Code Playgroud)