原创
前后端跨域问题汇总
温馨提示:
本文最后更新于 2020年02月24日,已超过 1,733 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
前后端跨域问题汇总
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;
}
}
- 本文标签: Vue Java
- 本文链接: http://www.lzhpo.com/article/107
- 版权声明: 本文由lzhpo原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权