一、問題
當(dāng)我實(shí)現(xiàn)前后端分離的時(shí)候,遇到了這個(gè)問題:
Access to XMLHttpRequest at ‘http://localhost:8080/xxx’ from origin ‘http://localhost:63342’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
二、問題產(chǎn)生的原因
后端響應(yīng)沒有帶上“ access-control-allow-origin”和“ access-control-allow-methods”標(biāo)頭。
三、解決方法
1. 問題出現(xiàn)在我們沒有帶標(biāo)頭,我們就帶上標(biāo)頭
response.addHeader( "Access-Control-Allow-Origin","*");//允許所有來源訪同
response.addHeader( "Access-Control-Allow-Method","POST,GET");//允許訪問的方式
這樣就解決了,但每次響應(yīng)都要帶上這兩個(gè)標(biāo)頭,覺得麻煩可以用下面這個(gè)方法。
2. 使用插件擴(kuò)展
Edge瀏覽器可直接在獲取擴(kuò)展里面搜索CORS,下載搜索到的第一個(gè)插件就行,當(dāng)我們需要跨域時(shí)就可以打開。
Google瀏覽器也可以安裝插件來解決,我用的是Moesif Origin & CORS Changer文章來源:http://www.zghlxwxcb.cn/news/detail-509049.html
3. 編寫配置文件
最佳解決方式!文章來源地址http://www.zghlxwxcb.cn/news/detail-509049.html
@Configuration
public class CORSConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
// 設(shè)置允許跨域的路徑
registry.addMapping("/**")
// 設(shè)置允許跨域請(qǐng)求的域名
.allowedOriginPatterns("*")
// 是否允許cookie
.allowCredentials(true)
// 設(shè)置允許的請(qǐng)求方式
.allowedMethods("GET", "POST", "DELETE", "PUT")
// 設(shè)置允許的header屬性
.allowedHeaders("*")
// 跨域允許時(shí)間
.maxAge(3600);
}
}
到了這里,關(guān)于解決跨域問題:Access to XMLHttpRequest at ‘http://localhost:8080/xxx‘ No ‘Access-Control-Allow-Origin‘ head的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!