我通过 javascript fetch 调用身份验证服务来获取访问令牌。该服务是一个简单的 RESTful 调用。我可以使用 fiddler 看到调用成功(带有 200 响应和 json 数据)。然而,获取响应似乎从未被调用。下面是一个片段:
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)
})
执行上面的 fetch 时,没有任何 console.logs 被执行......似乎只是挂起。但提琴手却另有说法。有什么想法吗?
您可能遇到了 CORS 起源策略问题。为了解决这个问题,您需要一些权限来访问 API 的服务器端。特别是,您需要在 php 或另一个服务器端点的标头中添加一行:
<?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
?>
另外,请确保不要在服务器端点的标头中包含:
header("Access-Control-Allow-Credentials" : true);
使用 POST 请求获取代码的工作模型是:
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;
});
let menu = document.querySelector('.nav-menu');
let modal = document.querySelector('#modal-container');
let close = document.querySelector('.close');
menu.addEventListener('click', function () {
modal.style.display = "flex";
setTimeout(function () {
modal.style.opacity = "1";
}, 10);
});
close.addEventListener('click', function () {
modal.style.opacity = "0";
setTimeout(function () {
modal.style.display = "none";
}, 300);
});
document.addEventListener("DOMContentLoaded", function () {
const backToTopButton = document.getElementById('backToTop');
window.addEventListener('scroll', function () {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
backToTopButton.style.display = 'block';
} else {
backToTopButton.style.display = 'none';
}
});
backToTopButton.addEventListener('click', function () {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
});
});
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`