2

There are three code snippets below. A cookie does not show up in the browser with the first two approaches. A cookie does show up in the browser with the last approach but I am looking for an approach that lets me send an arbitrary response object (like TestResponse), not just a file.

Maybe another difference to note is that I'm sending an async request using the whatwg-fetch.js library for the first two snippets but hitting the route via browser refresh in the last snippet. I need the cookie to be set by the time an async request completes.

(Snippet 1)The below code snippet does not work as the cookie does not show up in the browser.

@PostMapping(value="/test")
public ResponseEntity<TestResponse> test(@RequestBody TestReq 
    testReq, HttpServletRequest req, HttpServletResponse res){

    String testMessage = testReq.getTestMessage();

    TestResponse testResponse = new TestResponse();
    testResponse.setTestMessage(testMessage);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Set-Cookie", "key="+"value");

    ResponseEntity<TestResponse> testResponseEntity
        = new ResponseEntity<TestResponse>(testResponse, headers, HttpStatus.OK);

    return testResponseEntity;

}

(Snippet 2) This next code snippet also does not work as the cookie does not show up in the browser.

@PostMapping(value="/test")
public ResponseEntity<TestResponse> test(@RequestBody TestReq 
    testReq, HttpServletRequest req, HttpServletResponse res){

    String testMessage = testReq.getTestMessage();

    TestResponse testResponse = new TestResponse();
    testResponse.setTestMessage(testMessage);

    ResponseEntity<TestResponse> testResponseEntity
        = new ResponseEntity<TestResponse>(testResponse, HttpStatus.OK);

    Cookie c = new Cookie("key", "value");
    res.addCookie(c);

    return testResponseEntity;

}

(Snippet 3) The following code works. The cookie shows up in my browser when I load localhost.

@GetMapping(value="/")
public String home(HttpServletRequest req, HttpServletResponse res){
    Cookie c = new Cookie("key","value");
    res.addCookie(c);
    return "views/app.html;
}
TheWebCoder
  • 63
  • 2
  • 6
  • Take a look [here](https://stackoverflow.com/questions/45823950/spring-restcontroller-not-setting-cookies-with-response). It might be relevant, if in Response Headers `Set-Cookie` exists, then `access-control-allow-origin` is missing and you should figure out CORS issues. – lzagkaretos Dec 16 '17 at 21:43
  • 1
    You're right, Set-Cookie was in the response headers. My issue was not as complicated as the one linked though. I just needed to add "credentials: same-origin " to my fetch. Thanks for pointing me in the right direction. – TheWebCoder Dec 17 '17 at 15:38

0 Answers0