不知道看到这篇文章的你,是不是也像我一样,本地启动了一个后端服务,又在本地启动了一个前端服务,然后在通信的过程中发现,跨域了!具体的现象如下:
Access to XMLHttpRequest at '<http://127.0.0.1:7803/user_status>' from origin '<http://localhost:3000>' 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.
很容易看懂,对吧?于是我进行了如下设置:
app := iris.New()
app.Use(CrossDomain)
func CrossDomain(c iris.Context) {
c.Header("Access-Control-Allow-Origin", "<http://localhost:3000>")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Allow-Headers", "X-Customer-Header")
c.Header("Access-Control-Request-Headers", "X-Customer-Header")
c.Header("Access-Control-Request-Method", "GET,POST,DEL,PUT")
c.Next()
}
然后再次请求,发现没有自定义请求头的请求可以成功,但是携带了自定义请求头的请求却还是失败,失败原因还是跨域!我明明设置了允许携带自定义请求头,为什么还是失败呢?
c.Header("Access-Control-Allow-Headers", "X-Customer-Header")
查了查 iris 的文档,进行了如下设置:
app := iris.New()
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
AllowedHeaders: []string{"X-Customer-Header"},
})
app.UseRouter(crs)
成功了!
这个问题的过程和解决办法在这里描述起来还是相对比较好理解的,但是,为什么上一种方法中允许携带自定义请求头的设置不生效?
网友评论