問(wèn)題描述
我正在春季構(gòu)建一個(gè)后端 REST API,而我的朋友正在構(gòu)建一個(gè) Angular JS 前端應(yīng)用程序來(lái)調(diào)用我的 API.我有一個(gè)帶有鍵 Authorization
的令牌標(biāo)頭和一個(gè)可以訪問(wèn)的值服務(wù),否則它會(huì)拒絕.從郵遞員和 REST 客戶端我能夠接收 API,但是在測(cè)試時(shí)他說(shuō)他在預(yù)檢時(shí)收到 401 Unauthorized Error.下面是我的 doFilterInternal 方法.
I am building a backend REST API in spring and my friend is building a Angular JS front end app to call my API.I have a token header with key Authorization
and a value which gives access to the service otherwise it refuses.From Postman and REST client I am able to receive the API but when tested he says he gets 401 Unauthorized Error on preflight.Below is my doFilterInternal method.
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers","Content-Type, Accept, X-Requested-With, Authorization");
}
但是當(dāng)他在 Angular JS 中使用令牌調(diào)用 API 時(shí),他得到了
But when he calls the API with the token in Angular JS he gets
所以我跟著這個(gè)答案這里 我添加了屬性
So I followed this answer here and I added the property
spring.mvc.dispatch-options-request=true
在 application.properties.But stillt 他的錯(cuò)誤似乎就像
in the application.properties.But stillt he error seems to be like
預(yù)檢響應(yīng)包含無(wú)效的 https 狀態(tài)代碼 401
感謝任何幫助.
推薦答案
這是避免預(yù)檢錯(cuò)誤的過(guò)濾器
Here is the filter which avoid the preflight error
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
LOG.info("Adding CORS Headers ........................");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
從帖子中找到它 Cross Origin Request Blocked Spring MVC Restful Angularjs
這篇關(guān)于如何指定 CORS 的響應(yīng)標(biāo)頭?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!