Springboot+vue separates the front and back ends to solve the problem of cross-domain and cookie local joint debugging

Background : A separate project built using vue on the front end, and a separate project built using springboot on the back end. When debugging on the same machine locally, you need to start the front-end and back-end projects. Vue starts port 9527 and springboot starts port 8083, which causes cross-domain problems and cross-domain cookie transmission problems.

The problems that arise : 1. How to connect different local ports? 2. How to solve the cross-domain problem? 3. How to solve the problem of cookie loss caused by cross-domain?

1. How to connect different local ports?

After the front end starts a port, such as 9527, the back end starts a different port such as 8083

The axios used by the front-end project vue, and then set the baseUrl of the back-end interface in the front-end, then the front-end and the back-end can be connected.

const service = axios.create({
  baseURL: 'http://127.0.0.1:8083'
})

2. How to solve the cross-domain problem?

The first point: the back-end solution of cross-domain problems . The following code can be easily solved: (There are four ways to solve cross-domain problems in the back-end. Here is the simplest one. For other ways, please refer to: https://blog.csdn.net/Mint6/article/details/ 104726325 )


/**
 * @Auther: Administrator
 * @Date: 2020/2/23 22:09
 * @Description:
 */
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                //当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
                .allowedOrigins("http://localhost:9527")
                //是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }

}

3. How to solve the problem of cookie loss caused by cross-domain?

First, modify the back-end code of the second question:. allowedOrigins("http://localhost:9527") cannot write * here , you must fill in the actual http://ip:port number of the front-end project

Secondly, modify the front-end code: withCredentials in axios , which is the first step of axios basic settings, set to true

const service = axios.create({
  baseURL: 'http://127.0.0.1:8083',
  withCredentials: true
})

Well, so far, the local joint debugging of the front-end and back-end separation project is no problem.

 

Guess you like

Origin blog.csdn.net/Mint6/article/details/104468530