前后端跨域问题汇总
前后端跨域问题汇总
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
解决办法1-前端Vue
// 网关地址 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版本之后的解决跨域问题:
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
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; } }
还没有评论,来说两句吧...