Search code examples
jqueryajaxgogoland

Go Code is not printing posted json value from jquery ajax


Issue details

Go Code is not printing posted json value from jquery ajax

Go Code Main

routing := chi.NewRouter()
routing.Post("/authenticate", AuthenticateRouter)

Go Code

func AuthenticateRouter(w http.ResponseWriter, r *http.Request) {
    username := r.PostForm.Get("username")
    fmt.Println(r.PostFormValue("username"))  //Not showing posted value
    fmt.Println(r.Form.Get("username"))       //Not showing posted value
    fmt.Println(r.Form.Get("username"))       //Not showing posted value
}

JQuery ajax code

$.ajax({
    "type": "post",
    "url": "authenticate",
    "contentType": "application/json; charset=utf-8",
    "dataType": "json",
    "data": JSON.stringify({
        "username": $(form).find("[name='username']").val(),
        "password": $(form).find("[name='password']").val(),
    }),
    beforeSend: function() {
    },
    success: function(response) {
        debugger;
    },
    error: function(response) {
        debugger;
    },
    complete: function(response) {
        debugger;
    }
});

html

<form class="loginForm form-signin"><br>    
    <input type="text" name="username" />
    <input type="password" name="password" />
    <button type="submit">Log In</button>
</form>

Solution

  • You are sending JSON data, but PostForm works with URL-encoded data. You can do:

    type authBody struct {
       Username string `json:"username"`
       Password string `json:"password"`
    }
    
    func AuthenticateRouter(w http.ResponseWriter, r *http.Request) {
       dec:=json.NewDecoder(r.Body)
       var body authBody
       if err:=dec.Decode(&body); err!=nil {
          // deal with err
       }
       // Work with body.Username and body.Password
    }