Cookie is not sent in XHR request / cross-domain

寵の児 提交于 2020-01-24 11:56:26

问题


Step 1

Client makes an HTTP request to GET https://sub.d0main.com/getWithCookie

Step 2

The request is proxied by nginx and routed to Spring Boot application, where it's handled:

GetMapping("/getWithCookie")
fun getWithCookie(response: HttpServletResponse) {
  val cookie = Cookie("longCookie", "42")
  cookie.maxAge = 500
  response.addCookie(cookie)
  response.sendRedirect("https://d0main.com/renderPage")
}

Step 3

The "/renderPage" endpoint produces an HTML+JS page which contains a submit button with the following handler:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://sub.d0main.com/postWithCookie', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.withCredentials = true;
xhr.send(JSON.stringify({}));

Step 4

Browser renders this page and user clicks the submit button. Note, the page address is https://d0main.com/renderPage and there's a cookie with domain sub.d0main.com.

Step 5

The request is proxied by nginx and routed to Spring Boot application, where it should be handled. The /postWithCookie mapping looks like

@PostMapping("/postWithCookie", consumes = [MediaType.APPLICATION_JSON_VALUE])
fun postWithCookie(
@CookieValue("longCookie") longCookie: Long) {
  // ...
}

But Spring Boot rejects the request with status code 400, because the required cookie parameter is missing. The actual response looks like:

{
  "timestamp":"2019-08-26T07:48:29.930+0000",
  "status":400,
  "error":"Bad Request",
  "message":"Missing cookie 'longCookie' for method parameter of type long",
  "path":"/postWithCookie"
}

How to fix this?


回答1:


Here is a good point to start to work with cookies and Spring Boot.

https://www.viralpatel.net/spring-mvc-cookie-example/



来源:https://stackoverflow.com/questions/57648676/cookie-is-not-sent-in-xhr-request-cross-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!