javascript - 使用fetch时status code =200,但是response.ok却是false

查看:1414
本文介绍了javascript - 使用fetch时status code =200,但是response.ok却是false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

背景:
使用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的属性不可读

这篇关于javascript - 使用fetch时status code =200,但是response.ok却是false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆