我有一个运行在localhost:8090上的服务器,我从运行在localhost:3000上的React应用程序向其发出请求。此请求的目的是执行一些操作,完成后,它将从后端重定向到https://www.google.com/。
前端:
function processReq() {
fetch(`http://localhost:8090/some-process`,
{
method: "GET",
headers: {
Accept: "application/json",
}
}
)
.then(response => {
console.log(response);
}).catch(err => console.log(err))
}
后端
r.GET("/some-process", handlers.DoProcess)
func DoProcess(c *gin.Context) {
// processes request
var w http.ResponseWriter = c.Writer
http.Redirect(w, c.Request, "https://www.google.com", http.StatusSeeOther)
}
所有这些都运行良好,但是我得到了一个如下所示的Cors错误
Access to fetch at 'https://www.google.com/' (redirected from 'http://localhost:8090/some-process') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
请注意,我在后端安装了cors,它看起来像这样
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
if c.Request.Method == "OPTIONS" {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
c.AbortWithStatus(204)
return
}
c.Next()
}
}```
2条答案
按热度按时间blmhpbnm1#
您的情况与Mongoose redirect not waiting for findByIDAndDelete的答案中描述的情况类似。
与其让服务器以重定向响应,不如让它以200OK响应并让客户端执行
当它接收到该响应时。
polhcujo2#
你看到cors错误的原因是google没有返回许可的访问控制头。
更根本的问题是,您试图将浏览器重定向为
fetch
请求的一部分,但这不会起作用;如果google允许跨源访问,那么在fetch调用中只会返回HTML响应,而这并没有多大用处。相反,您应该在服务器响应中返回200,并让客户端将浏览器窗口重定向到google。