Reputation: 2155
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?
Upvotes: 7
Views: 28689
Reputation: 11
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`
Upvotes: -1
Reputation: 21767
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;
});
Upvotes: 2