技術力をスコア化して市場価値をチェックしてみませんか?PR

ブログやSNSのアウトプットをAIが分析。技術力の順位を算出!自分の市場価値を測ってみませんか?

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

Comments

No comments

Let's comment your feelings that are more than good

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

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

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address