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

本文介绍了如何在开发和生产环境中配置前端的axios代理以解决跨域问题,同时详细讲解了Springboot中如何通过WebMvcConfigurerAdapter和@CrossOrigin注解实现后端的CORS设置。
部署运行你感兴趣的模型镜像

解决前端配置

首先如果是开发环境下,直接在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 {

}

您可能感兴趣的与本文相关的镜像

GPT-oss:20b

GPT-oss:20b

图文对话
Gpt-oss

GPT OSS 是OpenAI 推出的重量级开放模型,面向强推理、智能体任务以及多样化开发场景

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值