douzhi9939 2017-12-30 10:46
浏览 130
已采纳

从ANGULAR到GO的Http请求=>状态码:422无法处理的实体

Im am getting http 422 response somehow: Status Code:422 Unprocessable Entity

console message of fmt.Println(c) is:

&{{0xc04227c1c0 -1 200} 0xc0421b2100 0xc042086d10 [] [0x8fdc00 0x8fe950 0x97e310 0x97cf80] 3 0xc0421ea5a0 map[] []}

map should be filled myEmail and myPassword but it doesnt.Please Help me out.

Is there something wrong with the body or is it something related to web api?

Here is my http request:

this.http.post('http://localhost:8080/api/v1/users', {'email': 'myEmail', 'password': 'myPassword'}, httpOptions)
          .subscribe(data => {
          console.log('register___', data);
      });

Here is the httpOptions:

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json'
        , 'Access-Control-Allow-Origin': '*'
        , 'Access-Control-Allow-Headers': 'access-control-allow-origin, access-control-allow-headers'})
};

Here is the go web Api I'm using:

package main

import (
    "fmt"

    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/mattn/go-sqlite3"
)

type Users struct {
    email string `gorm:"not null" form:"email" json:"email"`
    password  string `gorm:"not null" form:"password" json:"password"`
}

func InitDb() *gorm.DB {
    // Openning file
    db, err := gorm.Open("sqlite3", "./data.db")
    // Display SQL queries
    db.LogMode(true)

    // Error
    if err != nil {
        panic(err)
    }
    // Creating the table
    if !db.HasTable(&Users{}) {
        db.CreateTable(&Users{})
        db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&Users{})
    }

    return db
}

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Add("Access-Control-Allow-Origin", "http://localhost:4200")
        c.Next()
    }
}

func main() {
    r := gin.Default()

    r.Use(Cors())

    v1 := r.Group("api/v1")
    {
        v1.POST("/users", PostUser)
        v1.OPTIONS("/users", OptionsUser)
        v1.GET("/users", GetUsers)
        v1.GET("/users/:id", GetUser)
        v1.PUT("/users/:id", UpdateUser)
        v1.DELETE("/users/:id", DeleteUser)
    }

    r.Run(":8080")
}

func PostUser(c *gin.Context) {

    fmt.Println("___herewego___")
    db := InitDb()
    defer db.Close()

    var user Users
    c.Bind(&user)
    fmt.Println(c)
    fmt.Println("_____")
    fmt.Println(user)

    if user.email != "" && user.password != "" {
        fmt.Println("geldim gördüm gidiyorum.....................")
        // INSERT INTO "users" (name) VALUES (user.Name);
        db.Create(&user)

        // Display error
        c.JSON(201, gin.H{"success": user})
    } else {
        // Display error
        c.JSON(422, gin.H{"error": "Fields are empty"})
    }

    // curl -i -X POST -H "Content-Type: application/json" -d "{ \"email\": \"Thea\", \"password\": \"Queen\" }" http://localhost:8080/api/v1/users
}

func GetUsers(c *gin.Context) {
    // Connection to the database
    db := InitDb()
    // Close connection database
    defer db.Close()

    var users []Users
    // SELECT * FROM users
    db.Find(&users)

    // Display JSON result
    c.JSON(200, users)

    // curl -i http://localhost:8080/api/v1/users
}

func GetUser(c *gin.Context) {
    // Connection to the database
    db := InitDb()
    // Close connection database
    defer db.Close()

    email := c.Params.ByName("email")
    var user Users
    // SELECT * FROM users WHERE id = 1;
    db.First(&user, email)

    if user.email != "" {
        // Display JSON result
        c.JSON(200, user)
    } else {
        // Display JSON error
        c.JSON(404, gin.H{"error": "User not found"})
    }

    // curl -i http://localhost:8080/api/v1/users/1
}

func UpdateUser(c *gin.Context) {
    // Connection to the database
    db := InitDb()
    // Close connection database
    defer db.Close()

    // Get id user
    email := c.Params.ByName("email")
    var user Users
    // SELECT * FROM users WHERE id = 1;
    db.First(&user, email)

    if user.email != "" && user.password != "" {

        if user.email != "" {
            var newUser Users
            c.Bind(&newUser)

            result := Users{
                email: newUser.email,
                password:  newUser.password,
            }

            // UPDATE users SET email='newUser.email', password='newUser.password' WHERE id = user.Id;
            db.Save(&result)
            // Display modified data in JSON message "success"
            c.JSON(200, gin.H{"success": result})
        } else {
            // Display JSON error
            c.JSON(404, gin.H{"error": "User not found"})
        }

    } else {
        // Display JSON error
        c.JSON(422, gin.H{"error": "Fields are empty"})
    }

    // curl -i -X PUT -H "Content-Type: application/json" -d "{ \"email\": \"Thea\", \"password\": \"Merlyn\" }" http://localhost:8080/api/v1/users/1
}

func DeleteUser(c *gin.Context) {
    // Connection to the database
    db := InitDb()
    // Close connection database
    defer db.Close()

    // Get id user
    email := c.Params.ByName("email")
    var user Users
    // SELECT * FROM users WHERE id = 1;
    db.First(&user, email)

    if user.email != "" {
        // DELETE FROM users WHERE id = user.Id
        db.Delete(&user)
        // Display JSON result
        c.JSON(200, gin.H{"success": "User #" + email + " deleted"})
    } else {
        // Display JSON error
        c.JSON(404, gin.H{"error": "User not found"})
    }

    // curl -i -X DELETE http://localhost:8080/api/v1/users/1
}

func OptionsUser(c *gin.Context) {

    c.Writer.Header().Set("Access-Control-Allow-Methods", "DELETE,POST, PUT")
    c.Writer.Header().Set("Access-Control-Allow-Headers",   "access-control-allow-headers,access-control-allow-origin,content-type")
    c.Next()
}
  • 写回答

1条回答 默认 最新

  • dongshi1188 2017-12-30 10:57
    关注

    You need to export the fields in your data structure:

    type Users struct {
        Email string `gorm:"not null" form:"email" json:"email"`
        Password  string `gorm:"not null" form:"password" json:"password"`
    }
    

    They are currently unexported, so only visible to your package. This means that packages that marshal/unmarshal your data structure will be unable to see the fields.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题