我曾多次遇到CORS问题,通常可以解决它,但我想通过从MEAN堆栈范式中看到这一点来真正理解。
之前我只是在我的快速服务器中添加了中间件来捕获这些东西,但它看起来像有某种预挂钩,使我的请求出错。
在preflight响应中,Access-Control-Allow-Headers不允许请求报头字段Access-Control-Allow-Headers
我假设我可以这样做:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers","*")
})
或者等价的,但这似乎不能解决问题。我当然也试过
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers","Access-Control-Allow-Headers")
})
还是不走运。
在花了差不多一天的时间后,我才发现添加下面两个代码解决了我的问题。
将此添加到Global.asax中
protected void Application_BeginRequest()
{
if (Request.HttpMethod == "OPTIONS")
{
Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
Response.End();
}
}
并在web配置中添加以下内容
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
</customHeaders>
</httpProtocol>
非常好,我在一个silex项目上使用了这个
$app->after(function (Request $request, Response $response) {
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set("Access-Control-Allow-Credentials", "true");
$response->headers->set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
$response->headers->set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
});
在尝试连接Django后端时,我也遇到了类似的问题:
在preflight响应中Access-Control-Allow-Headers不允许请求报头字段授权
经过几个小时的搜索,我终于在以下评论的帮助下解决了这个问题:
还要确保你拼写的授权是美式的,而不是英式的。那是我生命中的半小时,我不会再回来了。Thx美国!(叹息)
因此,给那些被卡住的人一个提示:检查一下你是否正确拼写了“Authorization”这个单词。如果你设置Access-Control-Allow-Headers = [" authorization "],你就允许了错误的头!
如果您试图在请求标头上添加自定义标头,则必须让服务器知道允许发生特定的标头。在过滤请求的类中执行此操作。在下面的例子中,自定义头名称为"type":
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, Authorization, type ");
response.setHeader("Access-Control-Expose-Headers","Authorization");
}
}