1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • The access control allow origin header comes as a part of the server's response. Can you paste the response headers here – Tanmay Nov 04 '17 at 14:06

1 Answers1

1

This happens because of CORS (Cross-Origin Resource Sharing)

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to let a user agent gain permission to access selected resources from a server on a different origin (domain) than the site currently in use.

For example, if you want to get a resource stored on http://foo.com sending a request from http://bar.com you should add Access-Control-Allow-Origin: * header in your response.

Sources: Server-Side Access Control (CORS) and Cross-Origin Resource Sharing (CORS)

Marco
  • 271
  • 2
  • 6