最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Fetch not getting a response - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Aug 24, 2019 at 12:58 Mark Fisher 1,2671 gold badge14 silver badges32 bronze badges asked Aug 8, 2016 at 16:44 Los MoralesLos Morales 2,1558 gold badges30 silver badges47 bronze badges 13
  • fetch is poorly supported, did you check that your browser supports it? developer.mozilla/en-US/docs/Web/API/Fetch_API – I wrestled a bear once. Commented Aug 8, 2016 at 16:47
  • also, that url should be in quotes... – I wrestled a bear once. 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 ing back as a response in the fetch – Los Morales 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 (To demonstrate this, copy the Rlcm‌​ from your ment (or from any instance in this ment), and paste it into your browser's JS console and do "Rlcm‌".length and/or "Rlcm‌".charCodeAt(4)) – apsillers 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()... – Los Morales Commented Aug 8, 2016 at 18:01
 |  Show 8 more ments

2 Answers 2

Reset to default 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.');

// 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./php/phpGetPost.php';

fetch(endpoint, {
    method: 'POST',
    body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
    console.info('fetch()', response);
    return response;
});
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`
发布评论

评论列表(0)

  1. 暂无评论