2017-12-20 08:40
浏览 129

向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 (

func main() {
    router := mux.NewRouter()
    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
    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")
    } 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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题