I wanted to call an API which post the fallowing JSON:
"user": {
"username": "username",
"password": "pass",
"password_confirmation": "passconfirm",
"user_type": "admin"
},
"profile": {
"first_name": "firstname",
"last_name": "lastname"
}
It works great on Postman , Android and Python but unfortunately when I tested into Javascript with the following code:
function sendData() {
/*
get json value from HTML form.
*/
var firstname = document.forms["registerForm"]["first_name"].value;
var lastname = document.forms["registerForm"]["last_name"].value;
var pass = document.forms["registerForm"]["password"].value;
var passconfirm = document.forms["registerForm"]["password_confirmation"].value;
var username = document.forms["registerForm"]["username"].value;
var json_date = {
"user": {
"username": username,
"password": pass,
"password_confirmation": passconfirm,
"user_type": "admin"
},
"profile": {
"first_name": firstname,
"last_name": lastname
}
};
var data = JSON.stringify(json_date);
console.log(json_date);
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", send);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(data);
}
I get this error:
Reason: CORS hejquery‘Access-Control-Allow-Origin’ missing
I print json file with , console.log()
and then I saw my json file.
but not send to server.
I tried with jQuery too.
I must add this note, that server has been written with RubyOnRails.