遇到的跨域问题(使用fetchAPI的时候)

代码如下:

 fetch('http://localhost:3000/books', {
            method: 'post',
            body: JSON.stringify({
                uname: '张三',
                pwd: '456'
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(function(data) {
            return data.text()
        }).then(function(data) {
            console.log(data)
        })

出现报错 Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

错误很明显是一个跨域的错误,但是怎么解决呢?

  fetch('http://localhost:3000/books', {
        method: 'post',
        body: 'uname=wang&pwd=1314520',
        headers: {
            'Content-Type': 'application/X-WWW-form-urlencoded'
        }
    }).then(function(data) {
        return data.text()
    }).then(function(data) {
        console.log(data)
    })

使用上面的代码就不会报错,区别就在他们的 Content-Type 上面,在网上找了篇文章https://segmentfault.com/a/1190000009971254讲的比较详细,修改了后台代码后就没有报错了

后台代码使用 nodejs,在index中加入了

// 设置允许跨域访问该服务
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); //允许来自所有域名的请求
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); //请求允许的方法
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

设置了上面的跨域操作后就可以运行代码了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值