0

我的 API 使用 Echo 框架提供服务。当我fetch从我的 React 应用程序拨打电话时,我得到

Access to fetch at 'http://localhost:8080/myAPI' 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

即使我像这样设置 Echo:

    srv := echo.New()
    srv.HideBanner = true
    srv.Use(middleware.Logger())

    srv.Use(middleware.CORS())

我尝试了以下方法,但得到了相同的结果:

var (
    // DefaultCORSConfig is the default CORS middleware config.
    DefaultCORSConfig = middleware.CORSConfig{
        Skipper:      middleware.DefaultSkipper,
        AllowOrigins: []string{"*"},
        AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete, http.MethodOptions},
        AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAccessControlAllowOrigin, echo.HeaderAccessControlAllowMethods},
    }
)

srv.Use(middleware.CORSWithConfig(DefaultCORSConfig))

在响应中,我没有看到access-control-allow-origin标题。即使我输入,我也会得到相同的localhost:3000结果AllowOrigins

4

1 回答 1

0

问题是echo.New()在代码的其他地方再次调用它,从而消除了对 的调用srv.Use(middleware.CORS()),这是允许跨源调用所需的全部内容。

于 2021-11-04T02:46:21.423 回答