Have been digging this for few hours now.
I have vue.js code:
$(document).ready(function() {
var vue = new Vue({
el: '#login',
data: {
logged_in: false,
username: "",
password: "",
csrf_token: "",
},
methods: {
login: function() {
$.ajax({
url: apiEndpoint + '/login/',
type: "POST",
dataType: "json",
dataType: 'json',
data: JSON.stringify({"username": username.value,
"password": password.value,
"csrf_token": this.csrf_token}),
success: (data) => {
alert(1);
}
});
return false;
},
getCsrfToken: function() {
$.ajax({
url: apiEndpoint + '/login/',
success: (data) => {
this.csrf_token = data["Csrf_Token"];
if(data["User_id"] !== "") {
this.logged_in = true;
}
}
});
}
}
});
vue.getCsrfToken();
});
And backend written in GO code:
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
fmt.Printf("METHOD - %s
", r.Method)
if r.Method == "POST" {
My server handler:
appmux := http.NewServeMux()
appmux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("../www/static"))))
appmux.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("../www/assets"))))
appmux.Handle("/login/", commonMiddlewares(http.HandlerFunc(loginHandler)))
appmux.Handle("/logout/", secure(http.HandlerFunc(logoutHandler)))
The browser sends OPTIONS request witch is fine. Then it triest to send a POST request and gets 400, bad request but backend doesnt even register the request(fmt.Print..).
Why does my Post request gets 400?
Thanks!
EDIT: PICS!!
You should test your code against a test server like: https://www.posttestserver.com/, then you can go to http://posttestserver.com/data/ and view your request as sent because it may not be sending what you think it is.