7

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?

13
  • fetch is poorly supported, did you check that your browser supports it? developer.mozilla.org/en-US/docs/Web/API/Fetch_API Commented Aug 8, 2016 at 16:47
  • also, that url should be in quotes... Commented Aug 8, 2016 at 16:48
  • 1
    Yes I've testing using fiddler solely and then fiddler monitoring http traffic when I use that javascript fetch(). The calls are all good, just nothing coming back as a response in the fetch Commented Aug 8, 2016 at 16:57
  • 2
    You have an invisible Unicode "ZERO WIDTH NON-JOINER" character (char code 8204) after the m in ...Rlcm... in your X-SourceFiles header. This appears to be causing issues; at least it did when I tested it on test-cors.org (To demonstrate this, copy the Rlcm‌​ from your comment (or from any instance in this comment), and paste it into your browser's JS console and do "Rlcm‌".length and/or "Rlcm‌".charCodeAt(4)) Commented Aug 8, 2016 at 17:22
  • 1
    no, no console.log statements were executed. It's like after the fetch call nothing gets executed after the 1st then()... Commented Aug 8, 2016 at 18:01

2 Answers 2

2

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;
});
Sign up to request clarification or add additional context in comments.

Comments

-1
let arr = []
let page = 1
let recBoxs = document.querySelector('.recent-boxs')
let loadElement = document.querySelector('.load-more')
let search = document.querySelector('.search-input')
let searchBtn = document.querySelector('.search-btn')
function getDataJson() {
    fetch(`http://localhost:3000/services?_page=${page}&_limit=3`)
        .then(response => response.json())
        .then(data => {
            arr.push(data);
            data.forEach(element => {
                recBoxs.innerHTML += `
        <div class="recent-box">
            <i onclick="addFavorite(${element.id})" class="fa-regular fa-heart" ></i>
            <div class="recent-image"><img src="${element.images}" alt="Image"></div>
            <div class="rec-box-p">${element.date}</div>
            <div class="rec-box-h2">${element.title}</div>
            <div class = "rec-box-btns">
             <button class="delete" onclick="boxsDelete(${element.id})">
             <i class="fa-solid fa-trash"></i></button>
             <button class = "update"><a href = "./update.html?id=${element.id}" target = "_blank"><i class="fa-solid fa-pencil"></i></a></button>
             <button class = "cart"><a href = "./details.html?id=${element.id}"><i class="fa-solid fa-cart-shopping"></i></a></button>
            </div>
        </div>
            `
            });
            return arr.flat();
        })
        .catch(error => console.error('Error fetching data:', error));
}
function boxsDelete(id) {
    axios.delete(`http://localhost:3000/services/${id}`)
    window.location.reload();
}
loadElement.addEventListener('click', () => {
    page++
    getDataJson()
})
function addFavorite(id) {
    axios.get(`http://localhost:3000/favorites?serviceId=${id}`)
        .then(response => {
            axios.get(`http://localhost:3000/services/${id}`)
                .then(response => {
                    axios.post("http://localhost:3000/favorites", response.data);
                });

        });
}
getDataJson()
searchBtn.addEventListener('click', function () {
    recBoxs.innerHTML = '';

    const searchTerm = search.value.trim();

    fetch(`http://localhost:3000/services?title_like=${searchTerm}`)
        .then(response => response.json())
        .then(data => {
            arr.push(data);
            data.forEach(element => {
                recBoxs.innerHTML += `
                <div class="recent-box">
                <i onclick="addFavorite(${element.id})" class="fa-regular fa-heart" ></i>
                <div class="recent-image"><img src="${element.images}" alt="Image"></div>
                <div class="rec-box-p">${element.date}</div>
                <div class="rec-box-h2">${element.title}</div>
                <div class = "rec-box-btns">
                 <button class="delete" onclick="boxsDelete(${element.id})">
                 <i class="fa-solid fa-trash"></i></button>
                 <button class = "update"><a href = "./update.html?id=${element.id}" target = "_blank"><i class="fa-solid fa-pencil"></i></a></button>
                 <button class = "cart"><a href = "./details.html?id=${element.id}"><i class="fa-solid fa-cart-shopping"></i></a></button>
                </div>
            </div>
                `;
            });
            search.value=''
            return arr.flat();
        })
        .catch(error => console.error('Error fetching data:', error));
});`enter code here`

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.