前言
之前在Windows10本地 调试一个旧项目,手机移动端用的是Uni-app,vue的版本是v2。后端是java spring-boot。运行手机移动端的首页请求后台接口老是提示错误信息。
错误信息如下:
Access to XMLHttpRequest at 'http://localhost:8080/api/industry/getIndustryList' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
翻译后 :
从源"http://localhost:8081"访问"http://localhost:8080/api/industry/getIndustryList"的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:请求的资源未包含"Access-Control-Allow-Origin"标头。
解决问题:
1,在uni-app项目 修改
javascript
"h5" : {
"title" : "",
"domain" : "",
"devServer" : {
"proxy" : {
"/api/": {
"target":"http://localhost:8080/api/",
"changeOrigin": true,
"pathRewrite": {"^/api": ""}
}
}
}
},
2,java端修改继承WebMvcConfigurer的重写addCorsMappings()方法代码
java
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 对所有路径应用
.allowedOrigins("http://localhost:8081") // 允许的来源,根据实际情况修改
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
.allowedHeaders("*") // 允许的头部
.allowCredentials(true) // 是否发送Cookie
.maxAge(3600); // 预检请求的有效期(秒)
}
}