前后端跨域问题汇总

2022-11-14 16:59:40 浏览数 (3)

前后端跨域问题汇总

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

解决办法1-前端Vue

代码语言:javascript复制
// 网关地址
const GATEWAY_HOST = process.env.GATEWAY_HOST || '127.0.0.1'
const GATEWAY_PORT = process.env.GATEWAY_PORT || '9180'

// 转发配置
module.exports = {
  proxyList: {
    '/api': {
      target: 'http://'   GATEWAY_HOST   ':'   GATEWAY_PORT,
      changeOrigin: true,
      pathRewrite: {
        '^/api': '/api'
      }
    }
  }
}

解决办法2-后端Java

SpringBoot2.x版本之后的解决跨域问题:

代码语言:javascript复制
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 WebMvcConfig implements WebMvcConfigurer {

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedHeaders("*")
                    .allowedMethods("*")
                    .maxAge(30 * 1000);
    }

}

解决办法3-Nginx

代码语言:javascript复制
location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

    if ($request_method = 'OPTIONS') {
        return 204;
    }
}

参考文章:https://segmentfault.com/a/1190000012550346

1 人点赞