Gin-Gonic(golang)服务器上的Axios POST无法正常运行

时间:2018-10-09 07:29:35

标签: go cors axios nuxt gin-gonic

我可以使用GET,但不能使用来自axios的POST将数据发送到gin-gonic golang服务器。它在邮递员中完美运行。当我使用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 [恢复] 2018/10/09-00:12:34恐慌恢复:
  POST / api / v1 / stripe / pay HTTP / 1.1
  主机:localhost:8080
  接受:application / json,text / plain, /
  接受编码:gzip,deflate,br
  接受语言:en-US,en; q = 0.9
  缓存控制:无缓存
  连接:保持活动状态
  内容长度:52
  内容类型:application / json; charset = UTF-8
  Dnt:1
  来源:http://localhost:3000
  语法:无缓存
  推荐人:http://localhost:3000/
  用户代理: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)
    西班牙语:reflectcall(nil,不安全。Pointer(d.fn),deferArgs(d),uint32(d.siz),uint32(d.siz))
  /用户/joealai/go/src/sovrin-mind-stripe/sm-stripe.go:150(0x15f9ee5)
    BuyProduct:恐慌(err)
  [GIN] 2018/10/09-00:12:34 | 500 | 1.079498ms | 127.0.0.1 | POST / api / v1 / stripe / pay

2 个答案:

答案 0 :(得分:2)

我认为问题不在于杜松子酒或杜松子酒,而不仅仅是您的电话。请注意,您正在访问c.PostForm值,但是在axios调用中,您没有发送表单值,而是发送了json,因此变量中的值为空。如果您使用的是Postman,我想您发送PostForm的情况很好,但在axios中却不行。我的建议是仍然发送Post(还添加一个content-type:application-json标头),并将c.Bind正文发送到struct或map [string] interface {},然后将其强制转换为您的特定类型处理程序。

答案 1 :(得分:0)

据我了解,在Go的基本Web服务器程序包中,gin-gonic并没有内置JSON POST检索。相反,我们需要使用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
相关问题