0

The guy responsible for API requests is gone for the week, so nothing can be done on server side.

fetch("https://url.com/api/login/", {
    method: "post",
    headers: {
        // 'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: JSON.stringify({
        username: "test@mail.com",
        password: "123"
    })
}).then(function (response) {
    return response.json();
}).then(function (myJson) {
    console.log(myJson);
});

It works on Postman, but as I heard, Postman doesn't follow the same security as browsers, therefore this isn't an issue for Postman. But I doubt this is the case, as the authors php-solution works fine.

This is an example of php-solution that works (He wrote it):

    function login($username, $password) {
        $curl = curl_init(); curl_setopt_array($curl, array(
            CURLOPT_URL => "https://url.com/api/login/",
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_POSTFIELDS => "username=".$username."&password=".$password,
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $authdata = json_decode($response);
        if ($authdata -> success) {
            //success
            return true;
        } else {
            //fail
            return false;
        }
    }

What's missing in my code? How can I make it work like his php solution. (Have no experience in php).

Any help is much appreciated.

EDIT:

What worked on Postman:

  • Raw json format in Body.
  • Adding values as Key and Value in x-www-form-urlencoded
stacky
  • 23
  • 1

1 Answers1

0

To solve this error you can do 3 things:

  1. Add your origin server side.
  2. Run your javascript on the same domain.
  3. Check this answer for disabling same origin policy in chrome. This will allow you to test your code until the guy responsible for de API returns.
Mike Bovenlander
  • 4,695
  • 4
  • 27
  • 43
  • Thanks for your response, I will check those options shortly. Btw, is my solution correct, meaning it's server side issue / or have to be on same domain? – stacky May 21 '18 at 12:10
  • Well, the browser blocks the request because the domain of the API is different then the domain your javascript runs on. When adding the Allow Origin line on the server. The server tells the browser (in the response headers) to Allow your javascript domain. So yes, that's server side. – Mike Bovenlander May 21 '18 at 12:19