【发布时间】:2017-08-17 10:54:46
【问题描述】:
我将数据保存到会话中,但随后我尝试将其读回,结果为空。 Spring MVC 是我的后端,Angular 4 是前端。
Java:
@RestController
@CrossOrigin(origins = "http://localhost:3009", allowCredentials = "true")
@RequestMapping(value = "api")
public class RestController {
@Autowired
MainLogic mainLogic;
@RequestMapping(value = "/data", method = RequestMethod.GET)
public List<Data> getData(HttpServletRequest httpServletRequest){
// user is null here )-:
User user = (User)httpServletRequest.getSession().getAttribute("user");
if (user == null) {
return null;
}
return mainLogic.getData();
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public LoginResult logIn(HttpServletRequest httpServletRequest, @RequestParam("username") String username, @RequestParam("password") String password){
LoginResult result = mainLogic.logIn(username, password);
if (result.getUser() != null) {
// user is not null here
httpServletRequest.getSession().setAttribute("user", result.getUser());
}
return result;
}
}
角度:
logIn(username: string, password: string): Observable<LoginResult>{
let result = this.http
.post(`${this.baseUrl}/login?username=${username}&password=${password}` , {headers: configuration.getHeaders(), withCredentials: true})
.map(response => response.json());
return result;
}
getData(): Observable<Affiliate[]>{
let results = this.http
.get(`${this.baseUrl}/data`, {headers: configuration.getHeaders(), withCredentials: true})
.map(response => response.json());
return results;
}
知道我在这里缺少什么吗?也许与 CORS 有关?
【问题讨论】:
-
你能检查一下 httpServletRequest.getSession() 在这两种情况下是否返回相同的对象吗?
-
@user7294900 刚试过,没用
-
@alexd 不是,第二次是不同的会话
-
@alexd 可能与 CORS 有关?
标签: javascript java spring angular spring-mvc