日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

GO + React + Axios Response to preflight request doesn't pass access control check: It does not hav

作者:魯尼的小寶貝 更新時間: 2022-03-15 編程語言

使用Go + Reat 使用 Axios 請求后端, 出現:

Access to XMLHttpRequest at 'http://127.0.0.1:20002/v1/user/login' from origin 'http://localhost:4444' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

后端是:

c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
c.Writer.Header().Add("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Add("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Headers,Content-Length,Accept,Authorization,X-Requested-With")
c.Writer.Header().Add("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS")

cCp := c.Copy()
path := cCp.Request.URL.Path
method := cCp.Request.Method

log.Info("http - " + c.ClientIP() + " " + path + " " + method)

然后網上找啊找啊, 有一個是:

package.json 這個文件里面添加

"proxy": {
    "/*": {
      "target": "http://127.0.0.1:20002",
      "changeOrigin":true
    }
  },

不行, 我只想說, 沒有進過自己去檢測 , 就隨便的搞, 這樣我的還是不行,

最后修改后端實現:

c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
c.Writer.Header().Add("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Add("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Headers,Content-Length,Accept,Authorization,X-Requested-With")
c.Writer.Header().Add("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS")

cCp := c.Copy()
path := cCp.Request.URL.Path
method := cCp.Request.Method


log.Info("http - " + c.ClientIP() + " " + path + " " + method)

if cCp.Request.Method == "OPTIONS" {
	c.Writer.WriteHeader(http.StatusOK)
	return
}else{
	c.Next()
}

老哥, 穩得很.就可以了

原文鏈接:https://blog.csdn.net/poem_2010/article/details/86382559

欄目分類
最近更新