Gin-Gonic (golang) 服务器不工作的 Axios POST
Axios POST on Gin-Gonic (golang) Server Not Working
我可以使用 GET,但我不能使用来自 axios 的 POST,将数据发送到我的 gin-gonic golang 服务器。它在 Postman 中完美运行。当我用 Axios 发送请求时,我在 return.
中什么也得不到
当我进入 gin-gonic 服务器时,它显示 return 出现了 500 错误。经过进一步检查,我发现 post 变量中的 none 已被 gin 访问。
当我使用 Postman 时,服务器 return 提供指定的数组。我有一种感觉,它可能与 headers 有关,但我真的很难过。我大约 6 个月前遇到过这个问题,但一直没有弄清楚。现在我记得为什么我没有继续使用 axios 和 nuxt :).
这里是 golang gin-gonic 服务器路由。
func initServer() {
router := gin.Default()
config := cors.DefaultConfig()
config.AddAllowHeaders("*",)
config.AllowAllOrigins = true
config.AllowMethods = []string{"POST", "GET"}
router.Use(cors.New(config))
v1 := router.Group("/api/v1/stripe")
{
v1.POST("/pay", BuyProduct)
v1.POST("/card", UpdateCard)
v1.GET("/products", GetAllProducts)
v1.GET("/products/id/:productId", GetProduct)
v1.GET("/products/types/:typeId", GetProductType)
v1.GET("/products/types", GetAllProductTypes)
}
// You can get individual args with normal indexing.
serverAddress := "127.0.0.1:8080"
if len(os.Args) > 1 {
arg := os.Args[1]
serverAddress = fmt.Sprintf("127.0.0.1:%v", arg)
}
router.Run(serverAddress)
}
这是在命中端点时处理路由器调用的接收器函数
func BuyProduct(c *gin.Context) {
postUserID := c.PostForm("userId")
postProductId := c.PostForm("productId")
token := c.PostForm("token")
userId, err := strconv.Atoi(postUserID)
if err != nil {
panic(err)
}
productId, err := strconv.Atoi(postProductId)
if err != nil {
panic(err)
}
custy := user.InitCustomer(int64(userId), token)
custy.GetStripeCustomerData()
custy.SelectProduct(products.NewProduct(int64(productId)))
custy.Purchase()
c.JSON(200, gin.H{"status": 200,
"product": custy.Product,
"user": *custy.Saver.User,
"subscriptions": *custy.Subscriptions,
"ch": custy.Logs,
})
return
}
这是我的 axios (nuxt) 代码。
async purchaseSubscription() {
const paid = await
this.$axios.$post('http://localhost:8080/api/v1/stripe/pay', { data: {
userId: "121",
productId: this.productId,
}, query: { } })
this.paid = paid
},
这是我在 gogin-gonic 服务器中得到的错误
2018/10/09 00:12:34 [Recovery] 2018/10/09 - 00:12:34 panic recovered:
POST /api/v1/stripe/pay HTTP/1.1
Host: localhost:8080
Accept: application/json, text/plain, /
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 52
Content-Type: application/json;charset=UTF-8
Dnt: 1
Origin: http://localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
strconv.Atoi: parsing "": invalid syntax
/usr/local/go/src/runtime/panic.go:502 (0x102aca8)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/Users/joealai/go/src/sovrin-mind-stripe/sm-stripe.go:150 (0x15f9ee5)
BuyProduct: panic(err)
[GIN] 2018/10/09 - 00:12:34 | 500 | 1.079498ms | 127.0.0.1 | POST /api/v1/stripe/pay
我认为问题不在于杜松子酒或不是杜松子酒,而在于您的电话。请注意,您正在访问 c.PostForm
值,但在您的 axios 调用中您没有发送表单值,而是发送了 json,因此在您的变量中该值为空。如果您使用的是 Postman,我想您发送 PostForm 的效果很好,但不是在您的 axios 中。我的建议是仍然发送一个 Post(同时添加一个 content-type: application-json header)和 c.Bind
body 到一个结构或一个map[string]interface{},然后在处理程序中转换为您的特定类型。
在 gin-gonic 中没有 JSON POST 检索,据我所知,在 Go 的基本 Web 服务器包中。相反,我们需要使用 c.GetRawData(),然后将结果解组为一个结构!由于 c.GetRawData() 包含 data: { userId: 121, productId: 12, token: tok_visa }
,该结构还必须包含 data
json 字段。我希望这可以帮助别人!谢谢@Carles
type Buy struct {
Data struct {
User int64 `json:"userId" binding:"required"`
Product int64 `json:"productId" binding:"required"`
Token string `json:"token"`
} `json:"data"`
}
func BuyProduct(c *gin.Context) {
a := Buy{}
b, err := c.GetRawData()
if err != nil {
panic(err)
}
json2.Unmarshal(b, &a)
userId := a.Data.User
productId := a.Data.Product
token := a.Data.Token
我可以使用 GET,但我不能使用来自 axios 的 POST,将数据发送到我的 gin-gonic golang 服务器。它在 Postman 中完美运行。当我用 Axios 发送请求时,我在 return.
中什么也得不到当我进入 gin-gonic 服务器时,它显示 return 出现了 500 错误。经过进一步检查,我发现 post 变量中的 none 已被 gin 访问。
当我使用 Postman 时,服务器 return 提供指定的数组。我有一种感觉,它可能与 headers 有关,但我真的很难过。我大约 6 个月前遇到过这个问题,但一直没有弄清楚。现在我记得为什么我没有继续使用 axios 和 nuxt :).
这里是 golang gin-gonic 服务器路由。
func initServer() {
router := gin.Default()
config := cors.DefaultConfig()
config.AddAllowHeaders("*",)
config.AllowAllOrigins = true
config.AllowMethods = []string{"POST", "GET"}
router.Use(cors.New(config))
v1 := router.Group("/api/v1/stripe")
{
v1.POST("/pay", BuyProduct)
v1.POST("/card", UpdateCard)
v1.GET("/products", GetAllProducts)
v1.GET("/products/id/:productId", GetProduct)
v1.GET("/products/types/:typeId", GetProductType)
v1.GET("/products/types", GetAllProductTypes)
}
// You can get individual args with normal indexing.
serverAddress := "127.0.0.1:8080"
if len(os.Args) > 1 {
arg := os.Args[1]
serverAddress = fmt.Sprintf("127.0.0.1:%v", arg)
}
router.Run(serverAddress)
}
这是在命中端点时处理路由器调用的接收器函数
func BuyProduct(c *gin.Context) {
postUserID := c.PostForm("userId")
postProductId := c.PostForm("productId")
token := c.PostForm("token")
userId, err := strconv.Atoi(postUserID)
if err != nil {
panic(err)
}
productId, err := strconv.Atoi(postProductId)
if err != nil {
panic(err)
}
custy := user.InitCustomer(int64(userId), token)
custy.GetStripeCustomerData()
custy.SelectProduct(products.NewProduct(int64(productId)))
custy.Purchase()
c.JSON(200, gin.H{"status": 200,
"product": custy.Product,
"user": *custy.Saver.User,
"subscriptions": *custy.Subscriptions,
"ch": custy.Logs,
})
return
}
这是我的 axios (nuxt) 代码。
async purchaseSubscription() {
const paid = await
this.$axios.$post('http://localhost:8080/api/v1/stripe/pay', { data: {
userId: "121",
productId: this.productId,
}, query: { } })
this.paid = paid
},
这是我在 gogin-gonic 服务器中得到的错误
2018/10/09 00:12:34 [Recovery] 2018/10/09 - 00:12:34 panic recovered:
POST /api/v1/stripe/pay HTTP/1.1
Host: localhost:8080
Accept: application/json, text/plain, /
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 52
Content-Type: application/json;charset=UTF-8
Dnt: 1
Origin: http://localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
strconv.Atoi: parsing "": invalid syntax
/usr/local/go/src/runtime/panic.go:502 (0x102aca8)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/Users/joealai/go/src/sovrin-mind-stripe/sm-stripe.go:150 (0x15f9ee5)
BuyProduct: panic(err)
[GIN] 2018/10/09 - 00:12:34 | 500 | 1.079498ms | 127.0.0.1 | POST /api/v1/stripe/pay
我认为问题不在于杜松子酒或不是杜松子酒,而在于您的电话。请注意,您正在访问 c.PostForm
值,但在您的 axios 调用中您没有发送表单值,而是发送了 json,因此在您的变量中该值为空。如果您使用的是 Postman,我想您发送 PostForm 的效果很好,但不是在您的 axios 中。我的建议是仍然发送一个 Post(同时添加一个 content-type: application-json header)和 c.Bind
body 到一个结构或一个map[string]interface{},然后在处理程序中转换为您的特定类型。
在 gin-gonic 中没有 JSON POST 检索,据我所知,在 Go 的基本 Web 服务器包中。相反,我们需要使用 c.GetRawData(),然后将结果解组为一个结构!由于 c.GetRawData() 包含 data: { userId: 121, productId: 12, token: tok_visa }
,该结构还必须包含 data
json 字段。我希望这可以帮助别人!谢谢@Carles
type Buy struct {
Data struct {
User int64 `json:"userId" binding:"required"`
Product int64 `json:"productId" binding:"required"`
Token string `json:"token"`
} `json:"data"`
}
func BuyProduct(c *gin.Context) {
a := Buy{}
b, err := c.GetRawData()
if err != nil {
panic(err)
}
json2.Unmarshal(b, &a)
userId := a.Data.User
productId := a.Data.Product
token := a.Data.Token