AngularJS和Spring引导应用程序的CORS域cook

AngularJS和Spring引导应用程序的CORS域cook

本文介绍了AngularJS和Spring引导应用程序的CORS域cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在使用AngularJS 1.6( http://localhost:8000 )和Spring boot( http://localhost:8080 ).当用户登录时,spring boot api将在响应中添加一个cookie,我可以在浏览器中看到该cookie.

Currently I am building a application using AngularJS 1.6 (http://localhost:8000), and Spring boot (http://localhost:8080). When the user log in, the spring boot api will add a cookie in the response, and I can see the cookie in the browser.

然后在另一个获取用户的请求中,使用了我的后端代码

Then in another request to get the user, my backend code use

httpServletRequest.getCookies()

获取cookie,但它始终返回null.

to get the cookie, but it always returns null.

当我使用jsp和spring boot时,它运行良好.所以我想知道这是否是跨域问题.

When I used jsp and spring boot, it works well. So I am wondering if it is a cross domain issue.

在后端,我已经添加了配置:

In the backend, I already added the configuration:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("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, remember-me");

有人可以给我一些建议吗?

Can anyone give me some suggestions?

谢谢,彼得

推荐答案

您是否尝试过AngularJS中的withCredentials选项?

Did you try the withCredentials option in AngularJS?

如果添加此配置,则在发送请求时,角度$ http服务将发送cookie.

If you add this configuration, the angular $http service will send the cookie when sending the request.

例如:

$http.post(url, {withCredentials: true, ...})

或为所有请求添加此配置:

or add this configuration for all requests:

 angular.module('myApp')
 .config(['$httpProvider', function($httpProvider) {
  $httpProvider.defaults.withCredentials = true;
}])
  1. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
  2. 带有凭据的AngularJS

这篇关于AngularJS和Spring引导应用程序的CORS域cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 17:45