问题描述
在javascript中发送一个POST请求, 提示CORS策略被拦截, 代码如下
var xhr = new XMLHttpRequest();
xhr.open("POST", webhook);
// xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("content-type", "application/json");
xhr.onload = () => console.log(xhr.responseText);
// xhr.onload = () => console.log(xhr.responseText);
// var data = '{"chatid":"${chat_id}","msgtype":"text","text":{"content":"<@${rtx}> Hello"}}'
var data = '{"chatid":"' + chat_id + '","msgtype":"text","text":{"content":"<@' + rtx + '> ' + msg + '"}}'
console.log(data)
xhr.send(data);
报错提示
has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response
serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
原因分析
报错是因为浏览器在检查CORS的时候, 发现POST请求资源的是其他网站, 会进行检查, 如果目标网站没有开启跨站资源访问, 就会失败.
解决方法
网上有多种不同的解决办法, 比如下载插件将浏览器的CORS策略关闭, 试了较多没有效果. 或者如果目标网站是自己搭建的, 修改反馈允许CORS.
我使用Fiddle, 将浏览器请求目标网站的返回结果改了, 强制CORS检查通过.
具体为:
打开Fiddle, 添加Rule, 修改与目标网址的OPTIONS方法通信返回response:
HTTP/1.1 200 Generated
Server: nginx
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: content-type
Content-Length: 24
Connection: keep-alive