doujiong2533 2017-12-20 08:40
浏览 136
已采纳

向Golang API发送请求以发送JSON和严格认证的JSON

While making a POST request to Golang API, if I send stringy-fied JSON data it returns success but when I send JSON data it returns error with status 403.

Please help me understanding this behavior and how can I send JSON data using a POST request method.

File: main.go

package main

import (
    "devmgmtv2/auth"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    router := mux.NewRouter()
    auth.AuthInit(router)
    ssid.SsidInit(router)
    headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
    originsOk := handlers.AllowedOrigins([]string{"*"})
    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
    router.HandleFunc("/auth/login", Login).Methods("POST", "OPTIONS")
    log.Fatal(http.ListenAndServe(":8000", handlers.CORS(headersOk, originsOk, methodsOk)(router)))
}

func Login(w http.ResponseWriter, r *http.Request) {
    //Create User Struct
    var user User
    json.NewDecoder(r.Body).Decode(&user)
    userPassword := getUserPassword(user.User)
    // call get value for that user
    // check for equality if true, return the structure
    // if false return error
    if user.Password == userPassword {
        w.Header().Set("Content-Type", "text/plain")
        w.Write([]byte("success"))
    } else {
        http.Error(w, "Forbidden", http.StatusForbidden)
    }
}
  • 写回答

1条回答 默认 最新

  • dtu72460 2017-12-20 10:38
    关注

    When sending JSON to any http server you always have to use JSON.stringify().

    Not doing so will result in sending [object Object]... There are client libraries that do this kind of heavy lifting for you, but behind the scenes the JSON is always send as a string.


    Node.JS handles it the same way... it receives the string representation and usually something like body parser is run on the incoming request to extract the JSON from the string. So it might happen here behind the scenes, but it still happens.

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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真