zl程序教程

您现在的位置是:首页 >  Java

当前栏目

springboot和vue交互产生跨域问题的解决办法(后端解决方法)

2023-02-18 16:28:37 时间

前言

hi,大家好,我是左手写helloworld,右手写bug的秋名山码民! 今天在利用springboot+vue整合开发一个网站的时候出现了bug,总结一下在开发中遇到的一个问题,关于解决在使用vue和springboot在开发前后端分离的项目时,如何解决跨域问题

为什么产生跨域问题?

前端调用的后端接口不属于同一个域,域名或端口不同,就会产生跨域问题,也就是说你的应用访问了该应用域名或端口之外的域名或端口。

显示请求是成功的,返回200,这便是产生了跨域问题

如果想更深入的了解,可以参考:浏览器的同源策略

springboot后端配置解决跨域

在springboot框架的后端想要解决跨域问题,只需要添加一个类CorsConfig,将下面的代码复制过去

package com.kob.backend.config;

/**
 * @Author 秋名山码神
 * @Date 2022/12/13
 * @Description
 */

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 CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");

    }
}