Solve the problem that the browser can directly get the data but the ajax post cannot

analysis

  1. Open the console and find this error message:
has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’ header co…
  1. And direct get has data, indicating that the server is normal
  2. Use the browser f12 to capture packets and find that the browser ajax asynchronous request does not obtain the JSON data of the server response
  3. With the parameter copy ajax asynchronous request address, put it directly in the browser and press Enter. It was found that the json data was successfully responded
  4. Using a professional fiddler to capture the package, I found that the ajax asynchronous post request server responded to the json data, but not in the browser.
  5. It can be concluded that the browser blocked the server's response data
Solution

doFilter()Set the response header in the server-side filter to solve the data problem of the browser shielding cross-domain request responses

HttpServletResponse response  = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;

//http://xxx.xxx.xxx.xxx是你的前端地址 不是80端口有端口请设置端口http://xxx.xxx.xxx.xxx:端口号
response.setHeader("Access-Control-Allow-Origin","http://xxx.xxx.xxx.xxx");
response.setHeader("Access-Control-Allow-Credentials","true");

filterChain.doFilter(request, response);

note

http://xxx.xxx.xxx.xxxIt http://xxx.xxx.xxx.xxx:80is different from the browser. If your front-end port is port 80, please do not http://xxx.xxx.xxx.xxxadd port 80 behind, please use it directlyhttp://xxx.xxx.xxx.xxx

Guess you like

Origin blog.csdn.net/qq_41490274/article/details/100561308