【问题标题】:Getting error method not allowed and content-type:text/plain不允许获取错误方法和内容类型:文本/纯文本
【发布时间】:2021-08-19 12:36:48
【问题描述】:

除了CreateGoal,我所有的路线都运行良好。每当我使用Post 方法添加数据时,它都会给我消息method not allowed。当我检查Get 方法标题内容类型时,它是 application/json 但是当我检查Post方法Headers Content-type,为text/plain;字符集=utf-8。所以我认为Content-type肯定有问题。我不明白如何解决这个问题。我已附上截图以供参考。
截图:
路线:

func Setup(app *fiber.App) {

    app.Get("/goals", controllers.GetGoals)
    app.Get("/goals/:id", controllers.GetGoal)
    app.Post("/goals/add", controllers.CreateGoal)
    app.Put("/goals/:id", controllers.UpdateGoal)
    app.Delete("/goals/:id", controllers.DeleteGoal)

}

控制器:


import (
    "strconv"
    "github.com/gofiber/fiber/v2"
)

type Goal struct {
  Id        int    `json:"id"`
  Title     string `json:"title"`
  Status        bool   `json:"status"`
}

var goals = []*Goal{
    {
        Id:        1,
        Title:     "Read about Promises",
        Status:         true,
    },
    {
        Id:        2,
        Title:     "Read about Closures",
        Status:         false,
    },
}

func GetGoals(c *fiber.Ctx) error {
    return c.Status(fiber.StatusOK).JSON(
    // "success":  true,
    // "data": fiber.Map{
            // "goals": goals,
        // },
        goals,
  )
}

func CreateGoal(c *fiber.Ctx) error {
    type Request struct {
        Title string `json:"title"`
    }

    var body Request
    err := c.BodyParser(&body)
    if err != nil {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "success": false,
            "message": "Cannot parse JSON",
            "error":   err,
        })
    }

    goal := &Goal{
        Id:        len(goals) + 1,
        Title:     body.Title,
        Status: false,
    }

    goals = append(goals, goal)

    return c.Status(fiber.StatusCreated).JSON(fiber.Map{
        "success": true,
        "data": fiber.Map{
            "goal": goal,
        },
    })
}

【问题讨论】:

    标签: http go post postman


    【解决方案1】:

    POST 方法的应用程序中,您的端点是/goals/add。但是在 Postman 中,你调用了 /goals

    在应用程序中 /goals 期待 GET 请求。这就是为什么不允许有方法的原因。

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 2011-05-24
      • 2014-01-15
      • 1970-01-01
      • 2012-02-15
      • 2016-07-13
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多