javascript - session 奇怪地返回 null

标签 javascript java spring angular spring-mvc

我将数据保存到 session 中,但随后我尝试将其读回,结果为空。 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;
}
}

Angular :

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 有关?

最佳答案

你能检查一下cookies是否被启用吗?

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

相关文章:

spring - 无法使用范围测试的 Maven 依赖项解析 @SpringBootTest

java - Eclipse 无法识别消息包 (f :loadBundle error)

multithreading - 如何使 Spring Boot @Scheduled 线程超时

javascript - 表达静态(): "Undefined is not a function"

javascript - 如何防止某些字符从 React 输入标签中删除?

javascript - 将 info.selectionText 的值传递给内容脚本

java - Scala 模式匹配 Java 枚举值

java - 如果不小心删除了.metadata,如何获取项目列表

javascript - 使用占位符信息正确构造数组,直到填充所选对象

java - "No match Found"使用 matcher 的 group 方法时