fetch请求,No 'Access-Control-Allow-Origin' header的解决方法,SpringBoot支持跨域
Failed to load http://localhost:8080/a/b: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
原因:服务器端不支持跨域访问
方法1:使服务器端支持跨域访问,前端不用配置。
添加maven:
<!-- https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter -->
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
</dependency>
在controller方法上添加注解@CrossOrigin,也可以配置指定的源,非指定的源无法访问
前端的fetch请求中,不用添加mode: "no-cors"
http://localhost:2000/访问时,会报错403,和 Failed to load http://localhost:8080/a/b: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2000' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
前端Fetch代码:
function fectchF4() {
// fetch('http://localhost:8080/weather/queryCurWeatherNull', { method: "GET", mode: "no-cors" })
fetch('http://localhost:8080/weather/queryCurWeatherNull', { method: "post" }) //大写小写的post均可
// fetch('http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E5%BC%A0%E7%A2%A7%E6%99%A8', { method: "GET", headers: { "Access-Control-Allow-Origin": "*" } })
.then(response => {
console.log(response.ok)
if (response.ok) {
return response.json()
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText
})
}
})
.then(data => {
console.log('data is', data)
alert(data[0].areaId)
})
.catch(error => {
alert(error.status + error.statusText)
if (error.status === 404) {
console.log(error.status + error.statusText)
} else if (error.status === 403) {
console.log(error.status + error.statusText)
}
})
}
亲测正确可用