当我从服务器进行重定向时出现CORS错误。

huangapple go评论185阅读模式
英文:

Cors Error When I do a redirect from the server

问题

我有一个运行在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) {

	// 处理请求
	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,代码如下:

r.Use(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()
	}
}
英文:

I have a server running on localhost:8090, which I make a request to from a React App running on localhost:3000 . The aim of this request is to perform some operations and when it is done, it does a redirect to https://www.google.com/ from the backend. This is what it looks like.

Frontend:

function processReq() {
  fetch(`http://localhost:8090/some-process`,
    {
      method: "GET",
      headers: {
        Accept: "application/json",
      }
    }
  )
  .then(response => {
      console.log(response);
    }).catch(err => console.log(err))
}

Backend

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)
}

All of these works well, but I get a Cors error that looks like this

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.

Mind you, I have setup cors on my backend and it looks something like this


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()
	}
}```

</details>


# 答案1
**得分**: 1

你的情况类似于 https://stackoverflow.com/questions/74365535/mongoose-redirect-not-waiting-for-findbyidanddelete 中回答的情况。

与其让服务器响应重定向,可以让它响应 200 OK,并让客户端执行以下代码:
```js
location.href = "https://www.google.com";

当客户端收到这个响应时。

英文:

Your situation is similar to the one described in the answer to https://stackoverflow.com/questions/74365535/mongoose-redirect-not-waiting-for-findbyidanddelete.

Instead of letting the server respond with a redirect, let it respond with 200 OK and have the client execute

location.href = &quot;https://www.google.com&quot;;

when it receives this response.

答案2

得分: 0

你看到CORS错误的原因是因为Google没有返回允许的访问控制头。

更根本的问题是,你试图在fetch请求中重定向浏览器,这是行不通的;即使Google允许跨域访问,你只会在fetch调用中返回HTML响应,这并没有太大用处。

相反,你应该在服务器响应中返回200,并让客户端重定向浏览器窗口到Google。

function processReq() {
  fetch(`http://localhost:8090/some-process`,
    {
      method: "GET",
      headers: {
        Accept: "application/json",
      }
    }
  )
  .then(response => {
      console.log(response);
      window.location.href = 'https://google.com';
    }).catch(err => console.log(err))
}
英文:

The reason you're seeing cors errors is because google is not returning permissible access control headers.

The more fundamental issue is you're trying to redirect the browser as part of a fetch request which won't work; if google did allow cross origin access, you would just be returning the HTML response in your fetch call which isn't that useful.

Instead, you should just return a 200 in your server response and have the client redirect the browser window to google.

function processReq() {
  fetch(`http://localhost:8090/some-process`,
    {
      method: &quot;GET&quot;,
      headers: {
        Accept: &quot;application/json&quot;,
      }
    }
  )
  .then(response =&gt; {
      console.log(response);
      window.location.href = &#39;https://google.com&#39;;
    }).catch(err =&gt; console.log(err))
}

huangapple
  • 本文由 发表于 2023年2月10日 01:46:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75402506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定