フロントはTypescriptとVue3、サーバーサイドはgo言語を使って実装しています。
フロントからサーバー側のAPIを叩いた際に以下のエラーが発生しており、サーバー側でCORSの設定を行ったんですが、こちらのエラーが解決しません。
分かる方いますでしょうか?
よろしくお願いいたします。
Access to XMLHttpRequest at 'http://localhost:8080/api/price/?money_received=350000&bouns=1000000&fixed_cost=120000&loan=43000&private=55000' from origin 'http://localhost:4173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
go側のソースを張っておきます。
- server/controllers/price_management_controllers.go
// controllers/price_management_controllers.go
package controllers
import (
"net/http"
"server/common"
"github.com/gin-gonic/gin"
)
type PriceInfo struct {
LeftAmount int `json:"left_amount"`
TotalAmount int `json:"total_amount"`
}
type Response struct {
PriceInfo PriceInfo `json:"result"`
}
func priceCalc(moneyReceived, bouns, fixedCost, loan, private int) PriceInfo {
var priceinfo PriceInfo
priceinfo.LeftAmount = moneyReceived - fixedCost - loan - private
priceinfo.TotalAmount = (priceinfo.LeftAmount * 12) + bouns
return priceinfo
}
func GetPriceInfo(c *gin.Context) {
data, err := common.IntgetPrameter(c, "money_received", "bouns", "fixed_cost", "loan", "private")
if err == nil {
res := priceCalc(data["money_received"], data["bouns"], data["fixed_cost"], data["loan"], data["private"])
response := Response{PriceInfo: res}
c.JSON(http.StatusOK, gin.H{"message": response})
} else {
c.JSON(http.StatusOK, gin.H{"message": err})
}
}
func CreateUser(c *gin.Context) {
// ユーザーの作成ロジック
c.JSON(http.StatusCreated, gin.H{"message": "User created"})
}
- server/routes/routes.go
// routes/routes.go
package routes
import (
"server/controllers"
"github.com/gin-gonic/gin"
)
func SetupRoutes(r *gin.Engine) {
Routes := r.Group("/api")
{
Routes.GET("/price", controllers.GetPriceInfo)
// Routes.POST("/", controllers.CreateUser)
}
}
- server/main.go
// main.go
package main
import (
"server/routes"
"github.com/gin-contrib/cors" // corsミドルウェアのインポート
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// CORSミドルウェアを追加
config := cors.DefaultConfig()
config.AllowOrigins = []string{"*"}
config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
r.Use(cors.New(config))
routes.SetupRoutes(r)
r.Run(":8080")
}