我曾多次遇到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")
})
还是不走运。
在接下来的js我的问题得到解决使用
const cors=micro_cors({
origin:"https://studio.apollographql.com",
allowMethods:['POST','GET','PUT','PATCH','DELETE','OPTIONS'],
allowCredentials:true,
allowHeaders:['X-Requested-With','X-HTTP-Method-Override','Content-Type','Authorization','Accept','Access-Control-Allow-Credentials','Access-Control-Allow-Origin' ]
})
然后把它吸进去
export default cors(async function handler(req, res) {
await serverStart
if(req.method==="OPTIONS"){
res.end()
return false
}
apolloserver.createHandler({path:"/api/graphql"})(req,res)
})
公认的答案是可以的,但我很难理解它。这里有一个简单的例子来说明。
在我的ajax请求我有一个标准的授权头。
$$(document).on('ajaxStart', function(e){
var auth_token = localStorage.getItem(SB_TOKEN_MOBILE);
if( auth_token ) {
var xhr = e.detail.xhr;
xhr.setRequestHeader('**Authorization**', 'Bearer ' + auth_token);
}
这段代码产生了问题中的错误。我必须在我的nodejs服务器中添加授权头:
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,**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");
}
}