背景:
使用node的express开一个服务器端口为9876,react APP使用fetch请求localhost:9876的资源,使用浏览器调试工具的network查看status是200,但是在fetch的then里面打印出来response是status:0,ok:false
fetch的代码:
fetch(`http://localhost:9876/login.html`, {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
log(response)
})
.catch(function(error) {
console.log('There has been a problem:' + error.message);
});
打印出来的response:
node代码:
var express = require('express');
var app = express();
app.use(express.static('login'));
app.post('/login.html',function(req, res){
res.writeHead(200,{"Content-Type":"text/plain"});
res.end("Hello world");
});
app.listen(9876, function () {
console.log('app listening on port 9876!');
});
找到原因:
发起的是跨域请求,给fetch的参数设置为
mode:"cors"
,然后node那里加一句app.use(require('cors')());
如果fetch设置为mode:"no-cors",可以请求成功,但是response的属性不可读