节点js TypeError:无法读取未定义的属性“ body”

时间:2020-01-30 13:24:51

标签: javascript node.js express

我正在为一个Udacity课程开发一个示例项目,并且为此感到惊讶。我试图从表单中捕获一些用户输入并发出发布请求以返回javascript对象,当我尝试使用节点js运行服务器时,出现错误:

TypeError: Cannot read property 'body' of undefined

这是项目的服务器代码:

server.js

projectData = {};

/* Express to run server and routes */
const express = require('express');

/* Start up an instance of app */
const app = express();

/* Dependencies */
const bodyParser = require('body-parser')
/* Middleware*/
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const cors = require('cors');
app.use(cors());

/* Initialize the main project folder*/
app.use(express.static('project1'));

const port = 8000;
/* Spin up the server*/
const server = app.listen(port, listening);
 function listening(){
    // console.log(server);
    console.log(`running on localhost: ${port}`);
  };

// GET route

const animalData = [];

app.get('/all', getData);

function getData(req, res){
  res.send(AnimalData)
  console.log(AnimalData)
}

// function sendData (request, response) {
//  response.send(projectData);
// };

// POST route
app.post('/add', callBack);

function callBack(req,res){
  res.send('POST received');
}

// POST an animal
const data = [];


  // TODO-Call Function



app.route('/addAnimal')
  .get(function (req, res) {
    res.sendFile('index.html', {root: 'project1'})
  })
  .post(addAnimal())

function addAnimal(req, res){
  newEntry = {
    animal: req.body.animal,
    facts: req.body.fact,
    fav: req.body.fav
  }

  data.push(req.body);
  res.status(200).send(req.body);
  animalData.push(newEntry)
  res.send(animalData)
  console.log(animalData)
};

这是客户端的代码:

app.js

function performActuion(e){
const fav = document.getElementById('fav').value;



const getAnimal = async (url) =>{
  const res = await fetch(url);
  try {
    const data = await res.json();
    console.log(data)
    return data;
  } catch(error) {
    console.log()
  }
};

/* Function to POST data */
const postData = async ( url = '', data = {})=>{
    console.log(data);
      const response = await fetch(url, {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      credentials: 'same-origin', // include, *same-origin, omit
      headers: {
          'Content-Type': 'application/json',
      },
      body: JSON.stringify(data), // body data type must match "Content-Type" header        
    });

      try {
        const newData = await response.json();
        console.log(newData);
        // console.log(newData);
        return newData.json()
        console.log(await response.json());
        return await response.json()
      }catch(error) {
      console.log("error", error);
      // appropriately handle the error
      };
  };

  // TODO-Call Function
  (async function(){
    let res = await postData('/addAnimal', (animal: data.animal, fact: data.fact, fav: fav));;
    console.log(res);
  })();

在本课程的示例中,该代码似乎可以正常工作,但是当我尝试在自己的终端上运行它时,我什至无法进行测试,因为遇到类型错误。任何帮助将不胜感激。

谢谢, 迈克

1 个答案:

答案 0 :(得分:0)

问题出在此代码中:

app.route('/addAnimal')
  .get(function (req, res) {
    res.sendFile('index.html', {root: 'project1'})
  })
  .post(addAnimal())

您实际上是在调用函数而不是将其用作回调,请使用以下代码:

app.route('/addAnimal')
  .get(function (req, res) {
    res.sendFile('index.html', {root: 'project1'})
  })
  .post(addAnimal)