ajax put请求的跨域问题

为什么下面的post没问题,但是put请求会报错:

XMLHttpRequest cannot load http://localhost:8001/service. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access.

客户端

    $.ajax({
        url: 'http://localhost:8001/man',
        method: 'POST',
        success: function (data) {
            console.log(data)
        }
    });
  $.ajax({
        url: 'http://localhost:8001/service',
        method: 'PUT',
        success: function (data) {
            console.log(data)
        }
    });

服务端

app.post('/man', function (req, res) {
    var body = req.body;
    console.log(body);
    if (body) {
        res.header("Content-Type", "application/json; charset=utf-8");
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
        res.send(body);
    }
});

app.put('/service', function (req, res) {
    res.header("Content-Type", "application/json; charset=utf-8");
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
    res.send(req.body);
});
阅读 10k
3 个回答

问题在于预请求,在发起PUT请求之前会先发起一次OPTIONS请求,报错是针对OPTIONS这次请求,请求没有检查到headers中设置的Access-Control-Allow-Origin


解决办法:
添加一个对于OPTIONS请求的处理

app.options('/service', function (req, res) {
    res.header("Content-Type", "application/json; charset=utf-8");
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
});

因为put不是简单请求,有关跨域,可以看看这个

我没记错的话, 在chrome下面Access-Control-Allow-Origin设置成*是不行的, 你必须显式的设置成会去调用http地址

你上面的场景应该是设置成

Access-Control-Allow-Origin: http://localhost:63343

如果你确实希望在chrome下面使用*要不试试 https://chrome.google.com/web... (我没有尝试过)

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