CORS错误对于使用React前端的Golang Fiber应用程序来说是一个问题。

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

CORS error for golang fiber with React front-end

问题

我正在使用golang的fiber服务器,设置如下:

package main

import (
	"go-auth/database"
	"go-auth/routes"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
)

func main() {
	database.Connect()
	app := fiber.New()

	routes.Setup(app)

	app.Use(cors.New(cors.Config{
		AllowHeaders:     "Origin, Content-Type, Accept, Content-Length, Accept-Language, Accept-Encoding, Connection, Access-Control-Allow-Origin",
		AllowOrigins:     "*",
		AllowCredentials: true,
		AllowMethods:     "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
	}))
	app.Listen(":3800")
}

我通过React的fetch方法调用它:

const response = await fetch('http://127.0.0.1:3800/api/register', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name,
        email,
        password
    })
}).then(response => response.json());
console.log(response);

我做错了什么吗?服务器端已经禁用了CORS。这是我收到的错误:

Access to fetch at 'http://127.0.0.1:3800/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

还有这个错误:

register.js:17 POST http://127.0.0.1:3800/api/register net::ERR_FAILED

请注意,我只翻译了你提供的代码和错误信息,不会回答关于翻译的问题。

英文:

I am using golang fiber server, setup like this:

package main

import (
	"go-auth/database"
	"go-auth/routes"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
)

func main() {
	database.Connect()
	app := fiber.New()

	routes.Setup(app)

	app.Use(cors.New(cors.Config{
		AllowHeaders:     "Origin, Content-Type, Accept, Content-Length, Accept-Language, Accept-Encoding, Connection, Access-Control-Allow-Origin",
		AllowOrigins:     "*",
		AllowCredentials: true,
		AllowMethods:     "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
	}))
	app.Listen(":3800")
}

I am calling it via React fetch:

    const response = await fetch('http://127.0.0.1:3800/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name,
            email,
            password
        })
    }).then(response => response.json());
    console.log(response);

Am I doing something wrong? CORS is disabled on the server side already. Here is the error I get:

Access to fetch at 'http://127.0.0.1:3800/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Also this error:

register.js:17          POST http://127.0.0.1:3800/api/register net::ERR_FAILED

答案1

得分: 7

发现了错误,希望能帮助其他人,只需要将routes.Setup(app)移动到设置CORS之后,这样就有意义了,我猜想是这样的 🤦‍♂️🤦‍♂️:

func main() {
    database.Connect()
    app := fiber.New()

    app.Use(cors.New(cors.Config{
        AllowHeaders:     "Origin,Content-Type,Accept,Content-Length,Accept-Language,Accept-Encoding,Connection,Access-Control-Allow-Origin",
        AllowOrigins:     "*",
        AllowCredentials: true,
        AllowMethods:     "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
    }))
    routes.Setup(app)
    app.Listen(":3800")
}
英文:

Found the error, hope it help someone else, literally jusst need to move routes.Setup(app) to AFTER setting CORS up, which makes sense I guess 🤦‍♂️🤦‍♂️:

func main() {
	database.Connect()
	app := fiber.New()

	app.Use(cors.New(cors.Config{
		AllowHeaders:     "Origin,Content-Type,Accept,Content-Length,Accept-Language,Accept-Encoding,Connection,Access-Control-Allow-Origin",
		AllowOrigins:     "*",
		AllowCredentials: true,
		AllowMethods:     "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
	}))
	routes.Setup(app)
	app.Listen(":3800")
}

答案2

得分: 0

遇到了同样的问题。我的CORS设置行是在app.Mount('/api/', subapp)行之后。将其移到mount之前,然后它就可以工作了。最好将其放在fiber.New()之后。

英文:

Had the same issue. My CORS setup line was right after an app.Mount('/api/', subapp) line. Moved it before the mount and it worked. Best put it right after fiber.New()

huangapple
  • 本文由 发表于 2022年8月8日 11:45:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/73272736.html
匿名

发表评论

匿名网友

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

确定