我正在从我的angularjs客户端应用程序中点击一个端点,当我正在执行该操作时,我在浏览器控制台中收到以下错误
选项http://localhost:8080/oauth/token XMLHttpRequest无法加载http://localhost:8080/oauth/token。无效的HTTP状态代码401
服务器端代码从客户端接受CORS。
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}

调用http://localhost:8080/oauth/token
的客户端代码
angular.module('frontendApp')
.factory('AuthServerProvider', function loginService($http, localStorageService, Base64, API_SERVER) {
return {
login: function (credentials) {
var data = "username=" + credentials.username + "&password="
+ credentials.password + "&grant_type=password&scope=read%20write&" +
"client_secret=123456&client_id=clientapp";
return $http.post(API_SERVER + 'oauth/token', data, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Authorization": "Basic " + Base64.encode("clientapp" + ':' + "123456")
}
}).success(function (response) {
var expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
response.expires_at = expiredAt.getTime();
localStorageService.set('token', response);
return response;
});
},
logout: function () {
// logout from the server
$http.post('api/logout').then(function () {
localStorageService.clearAll();
});
},
getToken: function () {
return localStorageService.get('token');
},
hasValidToken: function () {
var token = this.getToken();
return token && token.expires_at && token.expires_at > new Date().getTime();
}
};
});

答案 0 :(得分:5)
如果是OPTIONS请求,则不应进行进一步处理,即跳过对chain.doFilter(req, res)
的呼叫,例如:
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
response.addHeader("Access-Control-Allow-Origin", "*");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "content-type,access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, resp);
}