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));
}
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"
});