回应预检要求未通过访问控制检查的NodeJS/Heroku的/快递
问题描述:
我使用在Heroku上的快速应用。我尝试从另一个NodeJS应用程序对它进行RESTful请求。回应预检要求未通过访问控制检查的NodeJS/Heroku的/快递
下面是从Heroku的应用程序的一个片段,称为app.js
:
var express= require("express");
app.get("/results",function(req,res){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
});
下面是从一个应用程序,我在本地运行一个片段,local-app.js
:
var request= require("superagent");
var req= request.get("http://url-to-app-js.com?query=1").set(
"Access-Control-Allow-Origin", "http://url-to-app-js.com",
"Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS",
"Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With"
);
req.end(function(err,res){
// do things
});
当我运行local-app.js
,我得到这个在我的浏览器控制台错误:esponse to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我知道我可以运行浏览器,铬,具有一定的安全设置已关闭,但我需要能够在不这样做的情况下运行此操作。
我在做什么错?我如何解决它?
答
Access-Control-Allow-Origin
,Access-Control-Allow-Methods
,和Access-Control-Allow-Headers
是响应头。他们不应该出现在请求中。
通过添加非标头您做出请求预检请求,而不是一个简单的请求。 (您可能正在做其他事情,使其成为预检请求,但额外的头文件肯定无济于事)。
预先发送的请求在发出请求之前(在这种情况下为GET)发出OPTIONS请求以查明它是否被CORS允许。
当您收到一个GET请求,你只设置CORS响应头。由于您没有回应OPTIONS请求,因此浏览器拒绝发出GET请求。
没有ü以往任何时候都得到这个工作? –