fetch请求,No 'Access-Control-Allow-Origin' header的解决方法,SpringBoot支持跨域 - Go语言中文社区

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)
            }
        })
}

亲测正确可用

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u010002184/article/details/83001816
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 11:58:54
  • 阅读 ( 1219 )
  • 分类:Go Web框架

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢