使用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.Pathmethod := cCp.Request.Methodlog.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.Pathmethod := cCp.Request.Methodlog.Info("http - " + c.ClientIP() + " " + path + " " + method)if cCp.Request.Method == "OPTIONS" {c.Writer.WriteHeader(http.StatusOK)return}else{c.Next()}
老哥, 稳得很.就可以了