How to unmarshall json request from Axios, React












0














I'm working on REST communication between React frontend and Go backend, I have a problem with sending proper http post request. If I use curl everything works fine but when I use axios I get an empty structure (unmarshalling doesn't return error). It seems to me that generated requests should be exactly the same.



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"encoding/json"
"io/ioutil"
)

type Credentials struct {
Password string `json:"password", db:"password"`
Username string `json:"username", db:"username"`
}

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

if r.Method == "OPTIONS" {
return
}
if r.Method == "POST" {
// Read body
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
fmt.Println("Couldn't read request body")
http.Error(w, err.Error(), 500)
return
}

// Unmarshal
var creds Credentials
err = json.Unmarshal(b, &creds)
if err != nil {
fmt.Println("Couldn't unmarshal body")
http.Error(w, err.Error(), 500)
return
}
fmt.Println(creds)

fmt.Println("username:", creds.Username)
fmt.Println("password:", creds.Password)

w.WriteHeader(http.StatusOK)
return
}
}


My curl command:



curl -X POST -H "Content-Type: application/json" -d '{"username":"Username","password":"Password"}' "http://localhost:8000/api/rooms/signin"


React handler:



  handleSubmit = (event) => {
event.preventDefault();
var data = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"username": "Username",
"password": "Password",
}
};
axios.post('http://localhost:8000/api/rooms/signin', data)
.then(response => {
console.log(response);
})
.catch(error => console.log(error));
}









share|improve this question




















  • 1




    I didn't test it but you have a comma , at the end of your request body in axios and you don't have it in the curl command. So speaking JSON-wise , your curl command has the correct syntax. Json unmarshall should give this as an error but can you try removing the "comma" anyways ?
    – atayenel
    Nov 12 at 19:48












  • removed it, still the same
    – asdfgh
    Nov 12 at 19:50






  • 2




    Your axios.post arguments are wrong. See github.com/axios/axios#axiosposturl-data-config. Also axios by default sends the data as json, no need for the headers. You're calling axios.post so no need for method: 'POST'. Just data, but omit the body attribute.
    – mkopriva
    Nov 12 at 20:01












  • it worked, thank you!
    – asdfgh
    Nov 12 at 20:09
















0














I'm working on REST communication between React frontend and Go backend, I have a problem with sending proper http post request. If I use curl everything works fine but when I use axios I get an empty structure (unmarshalling doesn't return error). It seems to me that generated requests should be exactly the same.



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"encoding/json"
"io/ioutil"
)

type Credentials struct {
Password string `json:"password", db:"password"`
Username string `json:"username", db:"username"`
}

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

if r.Method == "OPTIONS" {
return
}
if r.Method == "POST" {
// Read body
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
fmt.Println("Couldn't read request body")
http.Error(w, err.Error(), 500)
return
}

// Unmarshal
var creds Credentials
err = json.Unmarshal(b, &creds)
if err != nil {
fmt.Println("Couldn't unmarshal body")
http.Error(w, err.Error(), 500)
return
}
fmt.Println(creds)

fmt.Println("username:", creds.Username)
fmt.Println("password:", creds.Password)

w.WriteHeader(http.StatusOK)
return
}
}


My curl command:



curl -X POST -H "Content-Type: application/json" -d '{"username":"Username","password":"Password"}' "http://localhost:8000/api/rooms/signin"


React handler:



  handleSubmit = (event) => {
event.preventDefault();
var data = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"username": "Username",
"password": "Password",
}
};
axios.post('http://localhost:8000/api/rooms/signin', data)
.then(response => {
console.log(response);
})
.catch(error => console.log(error));
}









share|improve this question




















  • 1




    I didn't test it but you have a comma , at the end of your request body in axios and you don't have it in the curl command. So speaking JSON-wise , your curl command has the correct syntax. Json unmarshall should give this as an error but can you try removing the "comma" anyways ?
    – atayenel
    Nov 12 at 19:48












  • removed it, still the same
    – asdfgh
    Nov 12 at 19:50






  • 2




    Your axios.post arguments are wrong. See github.com/axios/axios#axiosposturl-data-config. Also axios by default sends the data as json, no need for the headers. You're calling axios.post so no need for method: 'POST'. Just data, but omit the body attribute.
    – mkopriva
    Nov 12 at 20:01












  • it worked, thank you!
    – asdfgh
    Nov 12 at 20:09














0












0








0







I'm working on REST communication between React frontend and Go backend, I have a problem with sending proper http post request. If I use curl everything works fine but when I use axios I get an empty structure (unmarshalling doesn't return error). It seems to me that generated requests should be exactly the same.



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"encoding/json"
"io/ioutil"
)

type Credentials struct {
Password string `json:"password", db:"password"`
Username string `json:"username", db:"username"`
}

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

if r.Method == "OPTIONS" {
return
}
if r.Method == "POST" {
// Read body
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
fmt.Println("Couldn't read request body")
http.Error(w, err.Error(), 500)
return
}

// Unmarshal
var creds Credentials
err = json.Unmarshal(b, &creds)
if err != nil {
fmt.Println("Couldn't unmarshal body")
http.Error(w, err.Error(), 500)
return
}
fmt.Println(creds)

fmt.Println("username:", creds.Username)
fmt.Println("password:", creds.Password)

w.WriteHeader(http.StatusOK)
return
}
}


My curl command:



curl -X POST -H "Content-Type: application/json" -d '{"username":"Username","password":"Password"}' "http://localhost:8000/api/rooms/signin"


React handler:



  handleSubmit = (event) => {
event.preventDefault();
var data = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"username": "Username",
"password": "Password",
}
};
axios.post('http://localhost:8000/api/rooms/signin', data)
.then(response => {
console.log(response);
})
.catch(error => console.log(error));
}









share|improve this question















I'm working on REST communication between React frontend and Go backend, I have a problem with sending proper http post request. If I use curl everything works fine but when I use axios I get an empty structure (unmarshalling doesn't return error). It seems to me that generated requests should be exactly the same.



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"encoding/json"
"io/ioutil"
)

type Credentials struct {
Password string `json:"password", db:"password"`
Username string `json:"username", db:"username"`
}

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

if r.Method == "OPTIONS" {
return
}
if r.Method == "POST" {
// Read body
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
fmt.Println("Couldn't read request body")
http.Error(w, err.Error(), 500)
return
}

// Unmarshal
var creds Credentials
err = json.Unmarshal(b, &creds)
if err != nil {
fmt.Println("Couldn't unmarshal body")
http.Error(w, err.Error(), 500)
return
}
fmt.Println(creds)

fmt.Println("username:", creds.Username)
fmt.Println("password:", creds.Password)

w.WriteHeader(http.StatusOK)
return
}
}


My curl command:



curl -X POST -H "Content-Type: application/json" -d '{"username":"Username","password":"Password"}' "http://localhost:8000/api/rooms/signin"


React handler:



  handleSubmit = (event) => {
event.preventDefault();
var data = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"username": "Username",
"password": "Password",
}
};
axios.post('http://localhost:8000/api/rooms/signin', data)
.then(response => {
console.log(response);
})
.catch(error => console.log(error));
}






reactjs go






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 at 7:06









Flimzy

37.2k96496




37.2k96496










asked Nov 12 at 19:42









asdfgh

4792821




4792821








  • 1




    I didn't test it but you have a comma , at the end of your request body in axios and you don't have it in the curl command. So speaking JSON-wise , your curl command has the correct syntax. Json unmarshall should give this as an error but can you try removing the "comma" anyways ?
    – atayenel
    Nov 12 at 19:48












  • removed it, still the same
    – asdfgh
    Nov 12 at 19:50






  • 2




    Your axios.post arguments are wrong. See github.com/axios/axios#axiosposturl-data-config. Also axios by default sends the data as json, no need for the headers. You're calling axios.post so no need for method: 'POST'. Just data, but omit the body attribute.
    – mkopriva
    Nov 12 at 20:01












  • it worked, thank you!
    – asdfgh
    Nov 12 at 20:09














  • 1




    I didn't test it but you have a comma , at the end of your request body in axios and you don't have it in the curl command. So speaking JSON-wise , your curl command has the correct syntax. Json unmarshall should give this as an error but can you try removing the "comma" anyways ?
    – atayenel
    Nov 12 at 19:48












  • removed it, still the same
    – asdfgh
    Nov 12 at 19:50






  • 2




    Your axios.post arguments are wrong. See github.com/axios/axios#axiosposturl-data-config. Also axios by default sends the data as json, no need for the headers. You're calling axios.post so no need for method: 'POST'. Just data, but omit the body attribute.
    – mkopriva
    Nov 12 at 20:01












  • it worked, thank you!
    – asdfgh
    Nov 12 at 20:09








1




1




I didn't test it but you have a comma , at the end of your request body in axios and you don't have it in the curl command. So speaking JSON-wise , your curl command has the correct syntax. Json unmarshall should give this as an error but can you try removing the "comma" anyways ?
– atayenel
Nov 12 at 19:48






I didn't test it but you have a comma , at the end of your request body in axios and you don't have it in the curl command. So speaking JSON-wise , your curl command has the correct syntax. Json unmarshall should give this as an error but can you try removing the "comma" anyways ?
– atayenel
Nov 12 at 19:48














removed it, still the same
– asdfgh
Nov 12 at 19:50




removed it, still the same
– asdfgh
Nov 12 at 19:50




2




2




Your axios.post arguments are wrong. See github.com/axios/axios#axiosposturl-data-config. Also axios by default sends the data as json, no need for the headers. You're calling axios.post so no need for method: 'POST'. Just data, but omit the body attribute.
– mkopriva
Nov 12 at 20:01






Your axios.post arguments are wrong. See github.com/axios/axios#axiosposturl-data-config. Also axios by default sends the data as json, no need for the headers. You're calling axios.post so no need for method: 'POST'. Just data, but omit the body attribute.
– mkopriva
Nov 12 at 20:01














it worked, thank you!
– asdfgh
Nov 12 at 20:09




it worked, thank you!
– asdfgh
Nov 12 at 20:09












1 Answer
1






active

oldest

votes


















1














When you are doing post request with axios, one way to do is



axios({
method: 'post',
url: 'http://localhost:8000/api/rooms/signin',
data: {
"username": "Username",
"password": "Password"
},
config: { headers: {'Content-Type': 'application/json' }}
});


if you want you could add then statements here too.



else



axios.post('http://localhost:8000/api/rooms/signin', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
},
"username": "Username",
"password": "Password"
});





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269034%2fhow-to-unmarshall-json-request-from-axios-react%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    When you are doing post request with axios, one way to do is



    axios({
    method: 'post',
    url: 'http://localhost:8000/api/rooms/signin',
    data: {
    "username": "Username",
    "password": "Password"
    },
    config: { headers: {'Content-Type': 'application/json' }}
    });


    if you want you could add then statements here too.



    else



    axios.post('http://localhost:8000/api/rooms/signin', {
    headers: {
    'Content-Type': 'application/json',
    'Authorization': 'JWT fefege...'
    },
    "username": "Username",
    "password": "Password"
    });





    share|improve this answer


























      1














      When you are doing post request with axios, one way to do is



      axios({
      method: 'post',
      url: 'http://localhost:8000/api/rooms/signin',
      data: {
      "username": "Username",
      "password": "Password"
      },
      config: { headers: {'Content-Type': 'application/json' }}
      });


      if you want you could add then statements here too.



      else



      axios.post('http://localhost:8000/api/rooms/signin', {
      headers: {
      'Content-Type': 'application/json',
      'Authorization': 'JWT fefege...'
      },
      "username": "Username",
      "password": "Password"
      });





      share|improve this answer
























        1












        1








        1






        When you are doing post request with axios, one way to do is



        axios({
        method: 'post',
        url: 'http://localhost:8000/api/rooms/signin',
        data: {
        "username": "Username",
        "password": "Password"
        },
        config: { headers: {'Content-Type': 'application/json' }}
        });


        if you want you could add then statements here too.



        else



        axios.post('http://localhost:8000/api/rooms/signin', {
        headers: {
        'Content-Type': 'application/json',
        'Authorization': 'JWT fefege...'
        },
        "username": "Username",
        "password": "Password"
        });





        share|improve this answer












        When you are doing post request with axios, one way to do is



        axios({
        method: 'post',
        url: 'http://localhost:8000/api/rooms/signin',
        data: {
        "username": "Username",
        "password": "Password"
        },
        config: { headers: {'Content-Type': 'application/json' }}
        });


        if you want you could add then statements here too.



        else



        axios.post('http://localhost:8000/api/rooms/signin', {
        headers: {
        'Content-Type': 'application/json',
        'Authorization': 'JWT fefege...'
        },
        "username": "Username",
        "password": "Password"
        });






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 at 5:26









        BRjava

        1,35711731




        1,35711731






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269034%2fhow-to-unmarshall-json-request-from-axios-react%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python