LoginSignup
3
0

More than 1 year has passed since last update.

wailsにEchoを導入したら「blocked by CORS policy」が発生したのでCORS対応する

Last updated at Posted at 2022-03-19

go-1.17 wails-v2 beta echo-v4.7.2

前提

  • wailsに別のweb frameworkを用いたい
  • wailsにReactとEcho( https://echo.labstack.com/ )を用いてアプリケーションを作ってみた
  • CORSのエラーが発生した

結論

  • EchoにCORSの設定を行う
  • 勉強目的でWebフレームワークを入れたがwailsでいろいろやってくれているので煩わしい気がする

事象

wailsにEchoを導入してfetchして見たところ下記エラーが発生しました。

image.png

wails.localhost/:1
Access to fetch at 'http://localhost:8080/users/1' from origin 'https://wails.localhost' has been blocked by CORS policy: 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.

よく見かけるやつですね。
それよりもwailsの内部ではHTTPSになっているんですね。

対象方法

EchoのmiddlewareでCORS対策をする
https://echo.labstack.com/middleware/cors/

AllowOriginsに https://wails.localhost と設定します。

main.go
func runServer() {
  e := echo.New()
  e.Use(middleware.Logger())
  e.Use(middleware.Recover())
+  e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
+    AllowOrigins: []string{"https://wails.localhost"},
+    AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
+  }))

  e.GET("/users/:id", getUser)
  e.Logger.Fatal(e.Start(":8080"))
}

呼び出し側はfetchで行っています。

App.tsx
  const handleEnterUserId = async function() {
    var apiUrl = `http://localhost:8080/users/${userId}`

    try {
      const response = await fetch(apiUrl , {method: 'GET', mode: 'cors'});
      const json = await response.json();
      setUser(json)
    } catch (error) {
      console.error(error);
    }
  }

3
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
3
0