vue跨域(前端配置/nginx+springboot配置)

前言

        学完vue,就想搞点前后端分离玩玩,然而在请求路径的时候却出现了跨域问题!因此我就想解决一下!开搞


1.前端配置解决跨域

1-1.创建文件

      vue-cli3的项目没有带那个config/index.js,只能自己创建一个叫vue.config.js
vue.config.js

1-2.写东西

image.png

1-3.在main.js中写

image.png

1-4.请求中写

image.png

1-5.成功

image.png

2.nginx+springboot配置解决跨域

2-1.vue.config.js中配置

vue.config.js

2-2.main.js中配置

main.js

2-3.springboot中配置

springboot
//方法一
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    /*是否允许请求带有验证信息*/
    corsConfiguration.setAllowCredentials(true);
    /*允许访问的客户端域名*/
    corsConfiguration.addAllowedOrigin("*");
    /*允许服务端访问的客户端请求头*/
    corsConfiguration.addAllowedHeader("*");
    /*允许访问的方法名,GET POST等*/
    corsConfiguration.addAllowedMethod("*");
    urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
    return new CorsFilter(urlBasedCorsConfigurationSource);
  }
}

//方法二SpringBoot2.4.写法
@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);
  }
}

2-4.nginx中配置

nginx

2-5.请求中写

image.png

2-6.成功

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。