0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoのechoでRESTAPIを作る時にCORSで怒られた時の対処法

Posted at

フロントエンドとバックエンドでドメインが違う場合、フロントエンドからバックエンドにfetchするとCORSで怒られる。
その際は以下のようにCORSWithConfigミドルウェアを設定してやればいい。

server.go
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins: []string{"http:///*リクエスト送る側のurl*/"},
    AllowHeaders:     []string{"authorization", "Content-Type", "Access-Control- 
    Allow-Origin"},
    AllowCredentials: true,
    AllowMethods: []string{http.MethodGet, http.MethodPost},
}))

e.POST("/login", login)
e.GET("/logout", logout)

e.Logger.Fatal(e.Start(":/*ポート番号*/"))

func login(c echo.Context) error {
    /*handle login*/
}

func  logout(c echo.Context) error {
    /*handle logout*/
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?