Possible CROS cross-domain problems in front-end and back-end separation projects

When working on a project, a new colleague asked me to look at a problem. The local code of the project is running normally, but the request reports 401 (or 404),

I opened the console and saw that I didn’t get the token. I thought it was a problem with the front-end, and then I went to see the file where the front-end got the token. After reading it for a long time and debugging for a long time, I can get the token normally. . Then I started to think about the back-end problem. Sure enough, the printed token showed null.

reason:

The query data found that the OPTIONS request before the query request was sent to check whether the server supports cross-domain requests, and it did not carry the token information in the headers , so the background could not obtain the token information after receiving the OPTIONS request, and returned it directly. So there are also cross-domain situations on the front end.

analyze:

In fact, two requests are sent, the first time is OPTIONS request, the second time is GET/POST... request;
In OPTIONS request, the parameters of the request header will not be carried, so the request header is obtained on the interceptor If it is empty, the custom interceptor intercepts successfully;
· If the first request fails, the second request GET/POST cannot be obtained...
· The first request does not have parameters, and the second request only has parameters ;

solve:

Just release the OPTIONS request.

In the interceptor, if the request is OPTIONSa request, it returns true, indicating that it can be accessed normally, and then the real GET/POSTrequest will be received

	    //放行登录请求
        if (request.getRequestURI().contains("/user/login")) {
            return true;
        }

        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }

        //取出请求头中的token
        String token = request.getHeader("token");
        System.out.println("token: " + token);
        if (StringUtils.isEmpty(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

Reference: Separation of front and back ends, in SpringBoot interceptor, the obtained request header token is NULL problem solving - Arbitrary233 - 博客园

The token in the request header cannot be obtained during the separation of the front and back ends - Gray Letter Network (Software Development Blog Aggregation)

Guess you like

Origin blog.csdn.net/BUG_CONQUEROR_LI/article/details/128299690