首页 > 解决方案 > 从 node.js 返回一个 json 响应到前端。

问题描述

因此,我正在尝试获取我的后端代码并从我在后端查询的 API 接收 json 响应。它正在返回一个对象,但是我的 json 要么埋在其中,要么不在那里。我可以将数据记录在节点中,但我无法将其发回。我试过 res-send、res-json 和 res-end。我不确定我哪里出错了。感谢您的任何帮助!

Web 应用程序控制台响应响应 {type: "basic", url: " http://localhost:3003/father ", 重定向: false, status: 200, ok: true, ...}

前端 JavaScript

  document.querySelector('.sub').addEventListener('click', function (e) {
  e.preventDefault()
  const wordSearched = document.querySelector('.word').value;
  fetch(`/${wordSearched}`)

   .then(function(answer) {
     console.log(answer);
  const number = answer.total_results;
  console.log(number);
  const tag = document.querySelector(".tagg").innerHTML = `The word 
  ${wordSearched} was used ${number} times!`;
  return tag
  })
   .catch(function(error) {
     console.log(' There has been a problem with the fetch operation: ', 
  error.message);
   })});

后端 node.js

    const express = require('express');
    const app = express();
    const morgan = require('morgan');
    const fetch = require('node-fetch');

    app.use(express.static('\public'));
    app.use(morgan('short'));

    app.get('/:wordSearched', (req, res) => {
      let word = req.params.wordSearched;
      console.log(word);
    fetch(`https://api.esv.org/v3/passage/search/?q=${word}`, {
    headers: {
    'Authorization': 'Token kkkdddd88383' // API Token
    }
    })
    .then(function(response) {
      return response.json()
    })
    .then(function(myJson) {
     const number = myJson.total_results;
      console.log(number);
      res.send(myJson) //cant send number??
        })
      .catch(function(error) {
        console.log(' There has been a problem with the fetch operation: ', error.message);
         })
         });

         //local host
        app.listen(3003, () => {
         console.log('server is up on 3003');
            });

标签: javascriptnode.jsjsonexpressweb

解决方案


所以我在阅读https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch上的 fetch 文档后发现了我的问题。我不得不打电话:

      .then(function(response) {
  return response.json()
})

在我的前端也是如此。我以前只在后端调用它,认为是我发送的 json。除非我在每一端都进行 .json() 调用,否则我不会得到答案。


推荐阅读