我将数据保存到会话中,但随后尝试将其读回,并且它为空。
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有关?

最佳答案

您可以检查cookie是否启用吗?

关于javascript - session 奇怪地返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45733223/

10-10 02:45