前言
? ? ? ? 之前在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項目 修改
"h5" : {"title" : "","domain" : "","devServer" : {"proxy" : {"/api/": {"target":"http://localhost:8080/api/","changeOrigin": true,"pathRewrite": {"^/api": ""}}}}},
2,java端修改繼承WebMvcConfigurer的重寫addCorsMappings()方法代碼
public class InterceptorConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") // 對所有路徑應用.allowedOrigins("http://localhost:8081") // 允許的來源,根據實際情況修改.allowedMethods("GET", "POST", "PUT", "DELETE") // 允許的方法.allowedHeaders("*") // 允許的頭部.allowCredentials(true) // 是否發送Cookie.maxAge(3600); // 預檢請求的有效期(秒)}
}