我知道回答自己的问题可能有点不好,但是在发布此问题几天后我就发现了问题。
一切都取决于浏览器如何管理CORS。当使用非“简单”的Javascript发出跨域请求(即GET请求-
解释该
query()功能为何起作用)时,浏览器将自动向指定的URL / URI发出HTTP OPTIONS请求,称为“ pre-
航班”请求或“承诺”。只要远程源返回200状态的HTTP状态代码以及响应标头中将接受的内容的相关详细信息,浏览器就会继续执行原始的Javascript调用。
这是一个简短的jQuery示例:
function makeRequest() { // browser makes HTTP OPTIONS request to www.myotherwebsite.com/api/test // and if it receives a HTTP status pre of 200 and relevant details about // what it will accept in HTTP headers, then it will make this POST request... $.post( "www.myotherwebsite.com/api/test", function(data) { alert(data); }); // ...if not then it won't - it's that simple.}我要做的就是在响应头中添加服务器将接受的详细信息:
// apply this rule to all requests accessing any URL/URIapp.all('*', function(req, res, next) { // add details of what is allowed in HTTP request headers to the response headers res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Credentials', false); res.header('Access-Control-Max-Age', '86400'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'); // the next() function continues execution and will move onto the requested URL/URI next();});然后在Express路由之前插入以下几行,以简单地为每个OPTIONS请求返回HTTP 200状态代码:
// fulfils pre-flight/promise requestapp.options('*', function(req, res) { res.send(200);});希望这可以帮助在此页面上偶然遇到相同问题的任何人。



