SpringBoot和Vue前后端请求跨域问题

SpringBoot和Vue前后端分离项目如何解决请求跨域问题

问题场景

刚开始来练手前后端分离的项目,后端boot项目地址端口为9090,前端地址端口为8080,所以如果不做任何处理去请求后端的方法的时候,前端页面F12就会报下面的内容
前端问题:
Access to XMLHttpRequest at ‘http://localhost:9090/api/city/getCitys’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

解决办法

1、前端添加配置信息

2、后端添加配置类

Vue:
1、 找到jest.config.js
2、 在合适的地方添加下面代码
以下是ES6的写法

devServer: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:9090',//这里为后端项目的地址
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },

在这里插入图片描述

3、 后端添加配置类,@ Configuration注解的类会再项目启动的时候自动加载

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

3、注意事项

因为改了配置文件,记得重启前后端项目

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值