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);

            })

报错提示:
批注 2020-06-09 133909.png
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.

我前面用x-www-form-urlencoded方式传递参数能正常返回,而且二者请求的是相同的接口,但是换成json方式就报上面的错误了

fetch('http://localhost:3000/books', {
                method: 'post',
                body: 'uname=lisi&pwd=123',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(function(data) {
                return data.text();
            }).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)
})

上网查了下多数都是说跨域请求问题,试过一遍也没有解决,如果是跨域请求问题,问什么有的报错,有的不报错呢

阅读 4.5k
1 个回答
    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://www.lilnong.top/cors/1010000022879873 这个接口

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题