简体   繁体   中英

JavaScript - API request (Access-Control-Allow-Origin error)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM