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

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

Cors Error When I do a redirect from the server

问题

我有一个运行在localhost:8090上的服务器,我从运行在localhost:3000上的React应用程序向其发出请求。这个请求的目的是执行一些操作,当操作完成后,后端会将其重定向到https://www.google.com/。代码如下:

前端:

  1. function processReq() {
  2. fetch(`http://localhost:8090/some-process`,
  3. {
  4. method: "GET",
  5. headers: {
  6. Accept: "application/json",
  7. }
  8. }
  9. )
  10. .then(response => {
  11. console.log(response);
  12. }).catch(err => console.log(err))
  13. }

后端:

  1. r.GET("/some-process", handlers.DoProcess)
  2. func DoProcess(c *gin.Context) {
  3. // 处理请求
  4. var w http.ResponseWriter = c.Writer
  5. http.Redirect(w, c.Request, "https://www.google.com", http.StatusSeeOther)
  6. }

所有这些都运行良好,但是我遇到了一个CORS错误,错误信息如下:

  1. 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,代码如下:

  1. r.Use(CORS())
  2. func CORS() gin.HandlerFunc {
  3. return func(c *gin.Context) {
  4. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  5. c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
  6. 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")
  7. c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
  8. if c.Request.Method == "OPTIONS" {
  9. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  10. c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
  11. 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")
  12. c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
  13. c.AbortWithStatus(204)
  14. return
  15. }
  16. c.Next()
  17. }
  18. }
英文:

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:

  1. function processReq() {
  2. fetch(`http://localhost:8090/some-process`,
  3. {
  4. method: "GET",
  5. headers: {
  6. Accept: "application/json",
  7. }
  8. }
  9. )
  10. .then(response => {
  11. console.log(response);
  12. }).catch(err => console.log(err))
  13. }

Backend

  1. r.GET("/some-process", handlers.DoProcess)
  2. func DoProcess(c *gin.Context) {
  3. // processes request
  4. var w http.ResponseWriter = c.Writer
  5. http.Redirect(w, c.Request, "https://www.google.com", http.StatusSeeOther)
  6. }

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

  1. 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

  1. func CORS() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  4. c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
  5. 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")
  6. c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
  7. if c.Request.Method == "OPTIONS" {
  8. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  9. c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
  10. 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")
  11. c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
  12. c.AbortWithStatus(204)
  13. return
  14. }
  15. c.Next()
  16. }
  17. }```
  18. </details>
  19. # 答案1
  20. **得分**: 1
  21. 你的情况类似于 https://stackoverflow.com/questions/74365535/mongoose-redirect-not-waiting-for-findbyidanddelete 中回答的情况。
  22. 与其让服务器响应重定向,可以让它响应 200 OK,并让客户端执行以下代码:
  23. ```js
  24. 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

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

when it receives this response.

答案2

得分: 0

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

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

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

  1. function processReq() {
  2. fetch(`http://localhost:8090/some-process`,
  3. {
  4. method: "GET",
  5. headers: {
  6. Accept: "application/json",
  7. }
  8. }
  9. )
  10. .then(response => {
  11. console.log(response);
  12. window.location.href = 'https://google.com';
  13. }).catch(err => console.log(err))
  14. }
英文:

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.

  1. function processReq() {
  2. fetch(`http://localhost:8090/some-process`,
  3. {
  4. method: &quot;GET&quot;,
  5. headers: {
  6. Accept: &quot;application/json&quot;,
  7. }
  8. }
  9. )
  10. .then(response =&gt; {
  11. console.log(response);
  12. window.location.href = &#39;https://google.com&#39;;
  13. }).catch(err =&gt; console.log(err))
  14. }

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:

确定