Bil*_*ill 3 go reactjs go-fiber
我正在使用 golang 光纤服务器,设置如下:
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")
}
Run Code Online (Sandbox Code Playgroud)
我通过 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);
Run Code Online (Sandbox Code Playgroud)
难道我做错了什么?服务器端已禁用 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.
Run Code Online (Sandbox Code Playgroud)
还有这个错误:
register.js:17 POST http://127.0.0.1:3800/api/register net::ERR_FAILED
Run Code Online (Sandbox Code Playgroud)
Bil*_*ill 10
发现错误,希望它对其他人有帮助,实际上只需要routes.Setup(app)在设置 CORS 之后移动到,我猜这是有道理的 \xe2\x80\x8d\xe2\x99\x82\xef\xb8\x8f\xe2\x80\x8d \xe2\x99\x82\xef\xb8\x8f:
func main() {\n database.Connect()\n app := fiber.New()\n\n app.Use(cors.New(cors.Config{\n AllowHeaders: "Origin,Content-Type,Accept,Content-Length,Accept-Language,Accept-Encoding,Connection,Access-Control-Allow-Origin",\n AllowOrigins: "*",\n AllowCredentials: true,\n AllowMethods: "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",\n }))\n routes.Setup(app)\n app.Listen(":3800")\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
4456 次 |
| 最近记录: |