为什么CORS错误没有得到解决?

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

Why is the cors error not getting resolved?

问题

cors是允许在Golang中的,使用以下代码:

func Register() *echo.Echo {
    e := echo.New()
    e.GET("/swagger/*", echoSwagger.WrapHandler) // 注册swagger
    validator.RegisterValidator(e)               // 注册验证器
    e.Use(middleware.Cors())  // 注册cors
    // ...
}
package middleware

import (
    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
)

func Cors() echo.MiddlewareFunc {
    return middleware.CORSWithConfig(middleware.CORSConfig{
        AllowOrigins:  []string{"http://localhost:3000"},
        AllowMethods:  []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
        AllowHeaders:  []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
        ExposeHeaders: []string{echo.HeaderContentLength},
    })
}

然而,即使我从React项目中的localhost:3000发送请求,cors错误仍然没有停止。

func (serverInfo *ServerInfo) ServerStart() {

    var databaseSet database.DatabaseInterface = &mysql.MysqlInfo{} // 数据库
    databaseSet.InitDatabase()                                      // 初始化数据库
    hosts := map[string]*Host{}                                     // 主机

    // API
    hosts[fmt.Sprintf("%v.%v:%v", "api.v1", os.Getenv(envkey.SERVER_URL), os.Getenv(envkey.PORT))] = &Host{apiV1Route.Register()}

    // Server
    e := echo.New()
    e.Use(middleware.Logger()) // 注册日志中间件

    e.Any("/*", func(c echo.Context) (err error) {
        req := c.Request()
        res := c.Response()
        host := hosts[req.Host]

        if host == nil {
            err = echo.ErrNotFound
        } else {
            host.Echo.ServeHTTP(res, req)
        }
        return
    })

    // e.Logger.Fatal(e.StartTLS(fmt.Sprintf(":%v", os.Getenv(envkey.PORT)), "housewhale.com+3.pem", "housewhale.com+3-key.pem"))
    e.Logger.Fatal(e.Start(fmt.Sprintf(":%v", os.Getenv(envkey.PORT))))
}

我已经花了几天时间解决这个问题,我该如何修复它?我尝试了手册或谷歌上找到的所有方法,但cors错误仍然存在。

英文:

cors is allowed in golang, with code like below

func Register() *echo.Echo {
	e := echo.New()
	e.GET("/swagger/*", echoSwagger.WrapHandler) // swagger 등록
	validator.RegisterValidator(e)               // 유효성검사 등록
	e.Use(middleware.Cors())  // cors 등록
......

package middleware

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func Cors() echo.MiddlewareFunc {
	return middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins:  []string{"http://localhost:3000"},
		AllowMethods:  []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
		AllowHeaders:  []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
		ExposeHeaders: []string{echo.HeaderContentLength},
	})
}

However, even if I send a request from (localhost:3000) in the react project, the cors error does not stop.

func (serverInfo *ServerInfo) ServerStart() {

	var databaseSet database.DatabaseInterface = &mysql.MysqlInfo{} // Database
	databaseSet.InitDatabase()                                      // 데이터베이스를 초기화합니다
	hosts := map[string]*Host{}                                     // Hosts

	// API
	hosts[fmt.Sprintf("%v.%v:%v", "api.v1", os.Getenv(envkey.SERVER_URL), os.Getenv(envkey.PORT))] = &Host{apiV1Route.Register()}

	// Server
	e := echo.New()
	e.Use(middleware.Logger()) // 로거등록

	e.Any("/*", func(c echo.Context) (err error) {
		req := c.Request()
		res := c.Response()
		host := hosts[req.Host]

		if host == nil {
			err = echo.ErrNotFound
		} else {
			host.Echo.ServeHTTP(res, req)
		}
		return
	})

	// e.Logger.Fatal(e.StartTLS(fmt.Sprintf(":%v", os.Getenv(envkey.PORT)), "housewhale.com+3.pem", "housewhale.com+3-key.pem"))
	e.Logger.Fatal(e.Start(fmt.Sprintf(":%v", os.Getenv(envkey.PORT))))
}

I've been spending days with this issue, how do I fix it? I've tried everything I've found in the manual or google, but the cors error doesn't go away.

答案1

得分: 1

有一个错误,没有附加错误信息,我将错误信息附在下面,当时问题已经解决。

从源头'http://localhost:3000'访问'https://api.v1.localhsot:8081/auth/retoken'被CORS策略阻止:预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'头。如果不透明的响应满足您的需求,请将请求的模式设置为'no-cors'以禁用CORS获取资源。

在服务器上,CORS没有正确允许,请配置服务器端以匹配请求。

例如,如果客户端将授权数据发送到标头中,则服务器也允许在标头中进行授权。设置必要的请求如下:

package middleware

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func Cors() echo.MiddlewareFunc {
	return middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins:     []string{"http://localhost:3000"},
		AllowMethods:     []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
		AllowHeaders:     []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAuthorization},
		ExposeHeaders:    []string{echo.HeaderContentLength, echo.HeaderSetCookie},
		AllowCredentials: true, // Add this line to allow credentials
	})
}
英文:

There was a mistake of not attaching the error, I attached the error as below and in that time the problem was solved.

Access to fetch at 'https://api.v1.localhsot:8081/auth/retoken' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

On the server, cors was not allowed correctly, please configure the server side to match the request

For example, if the client sends authorization data to the header, the server also allows authorization in the header. Set the necessary request like this

package middleware

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func Cors() echo.MiddlewareFunc {
	return middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins:     []string{"http://localhost:3000"},
		AllowMethods:     []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
		AllowHeaders:     []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAuthorization},
		ExposeHeaders:    []string{echo.HeaderContentLength, echo.HeaderSetCookie},
		AllowCredentials: true, // Add this line to allow credentials
	})
}

huangapple
  • 本文由 发表于 2023年3月26日 02:39:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75843803.html
匿名

发表评论

匿名网友

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

确定