首页 文章

Gin-Gonic(golang)服务器上的Axios POST无效

提问于
浏览
0

我可以使用GET,但我无法使用axios发送POST,将数据发送到我的gin-gonic golang服务器 . 它在Postman中完美运行 . 当我用Axios拍摄请求时,我得不到任何回报 .

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

当我使用Postman时,服务器返回指定的数组 . 我有一种感觉,它可能与 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)
}

这是接收器功能,在 endpoints 被命中时处理路由器调用

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 [恢复] 2018/10/09 - 00:12:34恐慌恢复:POST / api / v1 / stripe / pay HTTP / 1.1主机:localhost:8080接受:application / json ,text / plain,/ Accept-Encoding:gzip,deflate,br Accept-Language:en-US,en; q = 0.9 Cache-Control:no-cache连接:keep-alive内容长度:52内容类型:应用程序/ json; charset = UTF-8 Dnt:1来源: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,像Gecko)Chrome / 69.0.3497.100 Safari / 537.36 strconv.Atoi:解析“”:语法无效/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

2 回答

  • 0

    我认为问题不在于杜松子酒或杜松子酒,它__77898_重新访问 c.PostForm 值,但在你的axios中调用你're not sending a form values, you'重新发送一个json,所以在你的变量中值为空 . 如果你在发送PostForm时做得很好,但在你的axios中却没有 . 我的建议是仍然发送一个Post(也添加一个内容类型:application-json头)和 c.Bind 正文到一个struct或map [string] interface {}然后转换为你的处理程序中的特定类型 .

  • 2

    根据我的理解,在Go的基本Web服务器包中没有内置到gin-gonic的JSON POST Retrieval . 相反,我们需要使用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
    

相关问题