javascript - 使用fetch时status code =200,但是response.ok却是false
怪我咯
怪我咯 2017-04-11 12:18:11
[JavaScript讨论组]

背景:
使用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!');
});
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
ringa_lee

找到原因:
发起的是跨域请求,给fetch的参数设置为mode:"cors",然后node那里加一句app.use(require('cors')());如果fetch设置为mode:"no-cors",可以请求成功,但是response的属性不可读

高洛峰

Response.ok

Read only

Contains a boolean stating whether the response was successful (status in the range 200-299) or not.

不矛盾,请求发送成功了,但是没响应。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号