go - Gin-Gonic (golang) 服务器上的 Axios POST 不工作

标签 go axios nuxt.js go-gin

我可以使用 GET,但无法使用 axios 的 POST,将数据发送到我的 gin-gonic golang 服务器。它在 Postman 中完美运行。当我向 Axios 提交请求时,我没有得到任何返回。

当我进入 gin-gonic 服务器时,它显示它返回了 500 错误。经过进一步检查,我发现 gin 没有访问任何 post 变量。

当我使用Postman时,服务器返回指定的数组。我有一种感觉,这可能与标题有关,但我真的很难过。大约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
},

这是我在 go 中的 gin-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

最佳答案

我认为问题不在于 Gin 或不是 Gin ,而在于你的电话。请注意,您正在访问 c.PostForm 值,但在 axios 调用中您没有发送表单值,而是发送 json,因此在变量中该值为空。如果您使用的是 Postman,我想您发送 PostForm 的效果很好,但在您的 axios 中则不然。我的建议是仍然发送一个 Post (还添加一个 content-type: application-json header )并将 c.Bind 正文绑定(bind)到结构体或 map[string]interface{},然后转换为您的处理程序中的特定类型。

关于go - Gin-Gonic (golang) 服务器上的 Axios POST 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52715545/

相关文章:

php - 如何通过 Axios 将文件发送到 Laravel

go - 如何让 Go 程序使用更多内存?是推荐的吗?

go - Golang 是否支持可变参数函数?

javascript - 如何在同一个应用程序中使用 2 个具有不同 baseURL 的 Axios 实例 (vue.js)

ajax - 带有 auth 的 Laravel api 路由

vue.js - 使用 props 设置默认选择选项

nuxt.js - Nuxt Auth 上的访客中间件无法正常工作

go - 如何访问golang中的变量标签?

go - int 和 C.int 之间有什么区别?

javascript - 在 Nuxt.js 中使用 Vue-Meta 内联 Js