从node.js返回一个JSON响应到前端。

时间:2018-10-23 00:28:48

标签: javascript node.js json express web

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

Web应用程序控制台响应      响应{类型:“基本”,网址:“ http://localhost:3003/father”,重定向:false,状态:200,确定: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');
            });

1 个答案:

答案 0 :(得分:0)

因此,在阅读https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch上的获取文档后,我发现了问题。我不得不打电话给

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

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