【发布时间】:2023-02-10 01:56:46
【问题描述】:
我有一个在 localhost:8090 上运行的服务器,我从一个在 localhost:3000 上运行的 React App 向它发出请求。此请求的目的是执行一些操作,完成后,它会从后端重定向到 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()
}
}```
【问题讨论】:
-
你不能从客户端获取谷歌。您要改为重定向浏览器吗?
-
是的。我想在处理后重定向到谷歌。而不是发送 Json 响应