解决Vue前端和后端对接的跨域问题

解决前端配置

首先如果是开发环境下,直接在config文件夹下的index.js中的dev:{}中加入代理配置即可,我前端启动的路径是localhost:8080,后端访问路径是http://127.0.0.1:8081/overseas,这样就可以实现跨域的转发了。

proxyTable: {
    
    
      '/overseas': {
    
    

        target: 'http://127.0.0.1:8081/overseas',
        // target: 'http://192.168.1.7:8091/overseas',
       
        changeOrigin: true,
        pathRewrite: {
    
    
          '^/overseas': ''
        }
      },
    },

而在打包部署的生产环境中还需要配置一下axios的请求路径配置,如下

if (process.env.NODE_ENV === 'production') {
    
    
    console.log('生产环境');
    axios.defaults.baseURL = 'http://127.0.0.1:8081';// 路径
  } else {
    
    
    console.log('开发环境');
    axios.defaults.baseURL = 'http://127.0.0.1:8081';// 路径
  }

解决后端配置

除了前端需要设置跨域配置之外,后端相应的还需要设置允许跨域,如果是Springboot

1、在启动类中继承WebMvcConfigurerAdapter,重写其中的addCorsMappings方法

package com.example.springbootdemo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
@SpringBootApplication
public class SpringbootdemoApplication extends WebMvcConfigurerAdapter {
    
    
	public static void main(String[] args) {
    
    
		SpringApplication.run(SpringbootdemoApplication.class, args);
	}
	@Override
	public void addCorsMappings(CorsRegistry registry) {
    
    
 
		registry.addMapping("/**")
				.allowCredentials(true)
				.allowedHeaders("*")
				.allowedOrigins("*")
				.allowedMethods("*");
	}
}

2、在允许跨域请求的controller中使用@CrossOrigin 注解

import org.springframework.web.bind.annotation.CrossOrigin;
@CrossOrigin
@RestController
public class HelloWorldController {
    
    

}

猜你喜欢

转载自blog.csdn.net/david2000999/article/details/120930195
今日推荐