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

标签 javascript fetch

当我提交表单时,我没有返回任何数据,甚至在我的控制台中也没有。我正在尝试从 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/

相关文章:

javascript - 如何从 MongoDB 文档获取值(value)

javascript - jQuery:选择子元素的最后一个父元素

javascript - typeof 对象但不是数组

javascript - 关于用 `useState`初始化 `Date.now()`的问题

javascript - 试图将 jquery AJAX 转换为 Fetch API,如何设置 RequestHeader?

javascript - $ (':target' ) 在 Internet Explorer 11 中返回长度 0

javascript - ReactJS - 获取函数: Why am I getting uncaught (in promise) SyntaxError: Unexpected end of JSON input?

javascript - 每次渲染react时刷新组件状态

javascript - 在 Javascript 中获取 API 返回 [object, object]

javascript - 在使用.fetch时,是否可以将现有.fetch函数链接到一个更大的同步查询中?