vue使用fetch发送json格式的post请求报错解决方法

学习vue的fetch发送post的json格式数据请求时发生了跨域报错,自己解决不了,常规操作上网看博客,找了很久,都是说在后台服务器设置跨域允许,但是我明明设置了呀,我看的黑马教程,明明和视频一毛一样了还是不行…一脸问号,终于在找了很久后迎来了曙光…废话不多说…
前台发送请求的代码:

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

            })

后台服务器处理跨域代码:

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');
    res.header('Access-Control-Allow-Headers', 'mytoken');
    next();
});

响应代码:

app.post('/books', (req, res) => {
    
    
    res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
})

结果报错如下:
Access to fetch at 'http://localhost:3000/books/123' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
解决办法
把上面处理跨域的代码里的这三行合并到一行就可以了
res.header(“Access-Control-Allow-Headers”, “X-Requested-With”);
res.header(‘Access-Control-Allow-Headers’, ‘Content-Type’);
res.header(‘Access-Control-Allow-Headers’, ‘mytoken’);

更改后如下:在这里插入图片描述
参考链接:https://segmentfault.com/q/1010000022879873/a-1020000022881068

猜你喜欢

转载自blog.csdn.net/weixin_45295262/article/details/108626628
今日推荐