解决vue请求springBoot项目时跨域问题

由于浏览器同源策略的限制,如果请求url的协议、域名、端口号中有一项不同,就会产生跨域问题
当我们在本地开始前后端分离项目时,必然会启动不用的端口,所以就会发生跨域问题
比如我现在vue项目占用端口为8080,然后发axios请求到8082端口,浏览器就会报如下错:

我解决这个问题是在后端解决的,添加一个配置类实现WebMvcConfigurer接口,然后实现它的addCorsMappings方法,代码如下

package com.example.config;

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

/**
 * @description:开启跨域请求
 */

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")/*允许跨域访问的路径*/
                .allowedOriginPatterns("*")/*允许访问的客户端域名*/
//                .allowedOrigins("*")把这个换成allowedOriginPatterns单词
                .allowedMethods("*")/*允许访问的方法名,GET POST等("POST", "GET", "PUT", "OPTIONS", "DELETE")*/
                .allowCredentials(true)/*是否发送cookie*/
                .maxAge(3600)/*预检间隔时间*/
                .allowedHeaders("*");/*允许服务端访问的客户端请求头*/
    }
}


posted @ 2022-10-22 10:42  程长新  阅读(228)  评论(0)    收藏  举报