Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 节点js对象中未定义的元素_Javascript_Node.js_Express - Fatal编程技术网

Javascript 节点js对象中未定义的元素

Javascript 节点js对象中未定义的元素,javascript,node.js,express,Javascript,Node.js,Express,我对正在学习的在线课程的示例项目有问题。当我转到/fakeAnimalData时,我得到了要在HTML主体和终端中显示的元素animal和fact(但不在控制台中,它应该出现在哪里——为什么没有出现?),然后当我转到/addAnimal时,在我提交表单后,我在HTML主体中看到fav(但不在控制台中——为什么没有出现?)但我最大的问题是,在终端返回的对象中,动物和事实是未定义的。而且,出于某种原因,事实以事实的形式出现——为什么会这样 目标是从/fakeAnimalData获取数据,以显示在从/

我对正在学习的在线课程的示例项目有问题。当我转到/fakeAnimalData时,我得到了要在HTML主体和终端中显示的元素animal和fact(但不在控制台中,它应该出现在哪里——为什么没有出现?),然后当我转到/addAnimal时,在我提交表单后,我在HTML主体中看到fav(但不在控制台中——为什么没有出现?)但我最大的问题是,在终端返回的对象中,动物和事实是未定义的。而且,出于某种原因,事实以事实的形式出现——为什么会这样

目标是从/fakeAnimalData获取数据,以显示在从/addAnimal返回的终端中的对象中,因此我得到了所有三个返回并填充的元素——animal、fact和fav。我希望在终端和控制台中返回对象,但现在只在终端中返回对象

我做错了什么?这是我的代码:

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 = [];
const fakeData = {animal: "lion", fact: "a lion's roar can be heard five miles away"};

app.get('/fakeAnimalData', getFakeData);

function getFakeData(req, res) {
  res.send(fakeData)
  console.log(fakeData)
};

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
getAnimal('/fakeAnimalData')
.then(async function(data){
    console.log(data);
  let res = await postData('/addAnimal', {animal: data.animal, fact: data.fact, fav: fav});
  console.log(res);
});
};
任何帮助都将不胜感激

谢谢, 迈克

编辑:

我认为问题在于这部分代码不起作用:

getAnimal('/fakeAnimalData')
.then(async function(data){
    console.log(data);
  let res = await postData('/addAnimal', {animal: data.animal, fact: data.fact, fav: fav});
  console.log(res);
});
};
/fakeAnimalData返回{“动物”:“狮子”,“事实”:“五英里外可以听到狮子的吼声”}(但仅在HTML的主体中,而不是在控制台中)我希望上面的代码与下面的代码一起工作,将数据从/fakeAnimalData传输到我在/addAnimal上提交表单时返回的数据,因此返回的对象是{“animal”:“lion”,“fact”:“五英里外可以听到狮子的吼声”,“fav”:“从表单返回的数据”}。其要点是模拟从外部API进行API调用

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()
  }
};
编辑2:

我越来越近了。我把一段代码放错地方了。现在,当我提交代码时,我会将对象的所有三个元素都显示在HTML主体中,但是当我查看终端时,我仍然会看到动物和事实是未定义的,即使这些元素确实显示在HTML主体的结果中。app.js现在看起来像这样:

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

getAnimal('/fakeAnimalData')
.then(async function(data){
    console.log(data);
  let res = await postData('/addAnimal', {animal: data.animal, fact: data.fact, fav: fav});
  console.log(res);
});
};

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
getAnimal('/fakeAnimalData')
.then(async function(data){
    console.log(data);
  let res = await postData('/addAnimal', {animal: data.animal, fact: data.fact, fav: fav});
  console.log(res);
});
我觉得我离这里很近,但还不太近

编辑3:

我认为问题在于这个代码。它不会返回传递给函数的所有数据:

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
        console.log(await response.json());
        return await response.json()
      }catch(error) {
      console.log("error", error);
      // appropriately handle the error
      };
  };

我不能重现这个问题,我真的不认为需要完整的代码来演示您的问题。如果您设法将其压缩到所需的最小块(最好是作为可执行代码段发布),这将大大增加您获得相关答案的机会。当您在addAnimalok中构建新对象时,您将其称为“事实”,我认为我隔离了代码的两个部分,它们没有执行它们应该执行的操作。请查看我的编辑。您在登录到控制台之前发送了响应,这可能是一个问题。