解决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 {

}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值