Cross-domain solution between VUE3 front-end and SpringBOOT back-end

question

        Because it is the first time to try a front-end and back-end separation project, I have previously completed the front-end including login, registration and some core functions required by the project. However, the project lacked people, so I started working on the backend again, preparing to connect the login function first. The front-end and back-end interaction is nothing more than the front-end sending a request to the back-end, carrying specific parameters, and the back-end returns the corresponding data according to the front-end request path and parameters, but this is theoretical. In actual operation, how to use Axios correctly I have been troubled by sending data to a certain route on the backend for a long time.

Cross-domain front-end and back-end

        Cross-domain is divided into three types:

                Port cross-domain: source address http:127.0.0.1:8848 destination address http://127.0.0.1:8080

                Domain name cross-domain: source address http:127.0.0.1:8848 destination address http://22.33.55.66:8080

                Protocol cross-domain: source address http:127.0.0.1:8848 destination address https://22.33.55.66:8080

correct implementation

        Configure the baseURL of Axios as "/api" on the front end, and then set a proxy for it "http://localhost:8080" (backend address)

# 开发环境接口地址
VITE_API_URL = /api

# 开发环境跨域代理,支持配置多个
VITE_PROXY = [["/api","http://localhost:8080"]]

        In the backend, set the route of the user's Controller to "auth", and set the route of the login function to "login"

@RestController
@RequestMapping("auth")
@Tag(name = "auth", description = "认证相关的Controller")
public class AuthController {
    private final AuthService authService;

    @Autowired
    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @Operation(
            method = "POST",
            description = "用户登录",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    content = @Content(mediaType = "application/json")
            ),
            security = @SecurityRequirement(name = "", scopes = ""),
            summary = "用户登陆"
    )
    @PostMapping("login")
    public ResponseEntity<LoginVO> login(@RequestBody LoginParams login) {
        ResponseEntity<LoginVO> entity;
        System.out.println("");
        try {
            String token = authService.auth(login.getUsername(), login.getPassword());
            entity = ResponseWrapper.responseEntityAccept(new LoginVO(token));
        } catch (UserLoginErrorException e) {
            entity = ResponseWrapper.responseEntityFail(e.getMsg());
        }
        return entity;
    }
}

        Configure the url of axios as "auth/login" (this url was just set as baseURL), and PROT1 is auth

/**
 * @name 登录模块
 */
// 用户登录
export const loginApi = (params: Login.ReqLoginForm) => {
  return http.post<Login.ResLogin>(PORT1 + `/login`, params, { loading: false }); // 正常 post json 请求  ==>  application/json

};

question

        ​ ​Set the baseURL of Axios to http://localhost:8080

        This method successfully implemented the login function, but when I wanted to log out, I found that cross-domain problems occurred because the source address was http://localhost:8848 and the target address was http://localhost:8080. The port is cross-domain, so it cannot respond successfully without cross-domain configuration. (The bug has been fixed. If you can’t restore it, you won’t be able to post the picture anymore.)

        ​ ​Set the baseURL of Axios to /auth

        At this time, I seem to have understood the use of proxy by consulting the information, so I want to set the baseURL to auth, and then let all destination addresses with auth be proxy to http://localhost:8080. This method still does not work, although it has been possible The request went to the backend interface, but the request route was wrong because I still didn't understand the meaning of the following code when using vite.config.ts to create a proxy.

ewrite: path => path.replace(new RegExp(`^${prefix}`), ""),

Correct thinking     

        The front-end project is built using Vite. There is a field server in vite.config.ts that is specifically used to configure the server. We can use this configuration to solve cross-domain problems. Please see the code below

/**
 * 创建代理,用于解析 .env.development 代理配置
 * @param list
 */
export function createProxy(list: ProxyList = []) {
  const ret: ProxyTargetList = {};
  for (const [prefix, target] of list) {
    const httpsRE = /^https:\/\//;
    const isHttps = httpsRE.test(target);

    // https://github.com/http-party/node-http-proxy#options
    ret[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: path => path.replace(new RegExp(`^${prefix}`), ""),
      // https is require secure=false
      ...(isHttps ? { secure: false } : {})
    };
  }
  return ret;
}

        In this code, a proxy list is received and then each proxy is processed in a loop. Prefix and tartget are used to respectively retrieve the source address and proxy address in the proxy configuration, and then repackaged into key-value form. The most critical one is Yesrewrite:XX. The meaning of this code is to remove the source address in the final request address. For example, when configuring, the source address is /api. The proxy address is http://localhost:8080. If /api is not removed, there will be one more /api in the final request address, and the request cannot be sent correctly.

Guess you like

Origin blog.csdn.net/2201_75875170/article/details/133966584