Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Fetch not getting a response

I'm invoking an authentication service via javascript fetch to get an access token. The service is a simple RESTful call. I can see the call is successful using fiddler (with a 200 response and json data). However the fetch response never seems to get invoked. Below is a snippet:

const AUTHBODY = `grant_type=password&username=${username}&password=${password}&scope=roles offline_access profile`
const AUTHHEADER = new Headers({'Content-Type': 'application/x-www-form-urlencoded'})

const CONFIG = {
    method: 'POST',
    headers: AUTHHEADER,
    body: AUTHBODY
}

fetch('http://localhost:23461/connect/token', CONFIG).then(function(response) {
    console.log('response = ' + response)
    return response.json()
}).then(function(json) {
    console.log('json data = ' + json)
    return json
}).catch(function(error) {
    console.log('error = ' + error)
})

When executing the fetch above none of the console.logs gets executed... seems to just hang. But fiddler tells otherwise. Any ideas?

like image 739
Los Morales Avatar asked Aug 08 '16 16:08

Los Morales


1 Answers

You probably met with the CORS origin policy problem. To tackle this you need some rights to access the server side of your API. In particular, you need to add a line in the header of php or another server endpoint:

<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');

// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);

// Use $jsonObj
print_r($jsonObj->message);

...
// End php
?>

Also, make sure NOT to have in the header of your server endpoint:

header("Access-Control-Allow-Credentials" : true);

Model of working fetch code with POST request is:

const data = {
        message: 'We send a message to the backend with fetch()'
    };
const endpoint = 'http://example.com/php/phpGetPost.php';

fetch(endpoint, {
    method: 'POST',
    body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
    console.info('fetch()', response);
    return response;
});
like image 91
Roman Avatar answered Oct 02 '22 11:10

Roman