CORSに抵触して、クライアントとサーバ間でデータのやり取りがうまくいかない
解決したいこと
React側でPOSTした値をGolangのサーバ側で取得したい。
Goで作成したAPIをReact側で利用したい
発生している問題・エラー
クライアント・サーバ間でデータに受け渡しをしたいのですが、
CORSに抵触してしまいます。
Golang側でechoを使い
e.Use(middleware.CORS())
上記を記述して、localからのアクセスができるようにしたのですが、それでもうまくいきません。
また、POSTMANを利用してPOSTやGETをしましたが、そこではきちんとPOST、GETの処理が行えておりました。
該当するソースコード
package main
import (
"io"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
type Book struct {
Title string `json:"title" form:"title" query:"title"`
FirstName string `json:"firstname" form:"firstname" query:"firstname"`
LastName string `json:"lastname" form:"lastname" query:"lastname"`
}
type (
Stats struct {
Uptime time.Time `json:"uptime"`
RequestCount uint64 `json:"requestCount"`
Statuses map[string]int `json:"statuses"`
mutex sync.RWMutex
}
)
func NewStats() *Stats {
return &Stats{
Uptime: time.Now(),
Statuses: map[string]int{},
}
}
func (s *Stats) Process(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if err := next(c); err != nil {
c.Error(err)
}
s.mutex.Lock()
defer s.mutex.Unlock()
s.RequestCount++
status := strconv.Itoa(c.Response().Status)
s.Statuses[status]++
return nil
}
}
func (s *Stats) Handle(c echo.Context) error {
s.mutex.RLock()
defer s.mutex.RUnlock()
return c.JSON(http.StatusOK, s)
}
func ServerHeader(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set(echo.HeaderServer, "Echo/3.0")
return next(c)
}
}
func main() {
e := echo.New()
// Debug mode
e.Debug = true
//-------------------
// Custom middleware
//-------------------
// Stats
s := NewStats()
//Use関数でリクエストが飛んできたときに事前に決められた共通の処理ができる
//Proccessはリクエスト情報を取得する
e.Use(s.Process)
e.GET("/stats", s.Handle) // Endpoint to get stats
// Server header
e.Use(ServerHeader)
//CORS
e.Use(middleware.CORS())
// Handler
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.GET("/show", show)
e.POST("/save", save)
e.POST("/save1", save1)
e.POST("/books", books)
// Start server
e.Logger.Fatal(e.Start(":1323"))
}
// http://localhost:1323/show?team=x-men&member=wolverine
func show(c echo.Context) error {
// Get team and member from the query string
team := c.QueryParam("team")
member := c.QueryParam("member")
return c.String(http.StatusOK, "team:"+team+", member:"+member)
}
// e.POST("/save", save)
func save(c echo.Context) error {
// Get name and email
name := c.FormValue("name")
email := c.FormValue("email")
return c.String(http.StatusOK, "name:"+name+", email:"+email)
}
// e.POST("/books", books)
func books(c echo.Context) error {
name := c.FormValue("title")
firstName := c.FormValue("firstName")
lastName := c.FormValue("lastName")
b := &Book{}
b.Title = name
b.FirstName = firstName
b.LastName = lastName
if err := c.Bind(b); err != nil {
return err
}
return c.JSON(http.StatusCreated, b)
}
例)
import axios from "axios";
import './App.css';
axios.defaults.withCredentials = true;
function App() {
const handleSubmit = event => {
axios.get('http://localhost:1323/', {
}).then((res)=>{
console.log(res)
}).catch((res)=>{
console.log(res)
})
};
return (
<button onClick={event => handleSubmit(event)}>ボタン</button>
);
}
export default App;
自分で試したこと
React側でaxiosの呼びだしをjsonplaceholderで試したらきちんと呼び出しができました。
Golang側でPOSTMANを利用して、GET,POSTを行いましたが正常にうごきました。
CORSの公式ドキュメントをみて
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:3000"},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
}))
下記の方法を試しましたがそれでもだめでした
どうすればサーバ側でReact側のオリジンを許可できるのかご教示いただければ