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)

        }

    });

服务端

https://img.mukewang.com/5bd4083d0001bbb205870276.jpg

芜湖不芜
浏览 1826回答 1
1回答

ITMISS

问题在于预请求,在发起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"); });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript