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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料