gpt4 book ai didi

javascript - 获取请求不在控制台或前端返回任何数据

转载 作者:行者123 更新时间:2023-12-05 04:54:28 25 4
gpt4 key购买 nike

当我提交表单时,我没有返回任何数据,甚至在我的控制台中也没有。我正在尝试从 WHOIS 返回有关所搜索 URL 的详细信息,但没有得到任何返回。

谁能就为什么会出现这种情况提供任何建议?

这是我的前端脚本标签,在我的表单之后:

document.getElementById('search').addEventListener('submit', function(e) { e.preventDefault(); getDetails(); })
async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {}) {
return new Promise(function (resolve, reject) {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'text/html'
},
body: JSON.stringify(data)
}).then(async response => {
if (response.ok) {
response.json().then(json => resolve(json))
console.log(data);
} else {
response.json().then(json => reject(json))
}
}).catch(async error => {
reject(error)
})
})
}

在我的 express 后端,我正在使用 req.params.url 如果这有助于提供任何上下文...

我的 Status Code 是 200,在 Headers 选项卡中显示一切正常...

最佳答案

你混合使用了 promise 和 async 语法,这令人困惑,让我们先将其翻译为 awaitpromise (如果你可以使用 async then do,它比 Promise/then 更容易):

document.getElementById('search').addEventListener(
'submit',
function(e) {
e.preventDefault();
getDetails();
});

async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {})
{
// Fetch will throw an exception if it can't connect to the service
const response = await fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'text/html' },
body: JSON.stringify(data)
});

if (response.ok)
return await response.json();

// We could connect but got an error back from the service
// There may not be a response body, so response.json() or .body() might crash
throw new Error(`Error from server ${response.status}: ${response.statusText}`;

// We don't need catch, as any exception in an await will cascade up anyway
}

这使它更具可读性,很明显 getDetails 本身没有进行任何更改,它只是从服务返回 JSON。修复需要在事件监听器中 - 它需要对结果一些事情:

document.getElementById('search').addEventListener(
'submit',
async e => {
e.preventDefault();
const searchResult = await getDetails();

// Do something to show the results, populate #results
const resultsElement = document.getElementById('results');
resultsElement.innerText = JSON.stringify(searchResult);
});

关于javascript - 获取请求不在控制台或前端返回任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65745127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com