猿问

应用程序中未定义参考错误

尝试在表单上提交数据时,网络服务器给我一个错误,说Reference error: Item is not defined,但根据我的代码,一切看起来都不错。在我的代码中是否有任何对您来说很突出的东西可能导致这种情况?


我在玩 Const,但我不确定这是否是问题所在。


这是我的 Javascript 文件:


const express = require('express');

const app = express();

const bodyParser  = require('body-parser');

const mongoose = require('mongoose');

//specify where to find the schema

const Items = require('./models/item')

// connect and display the status 

mongoose.connect('mongodb://localhost:27017/items', { useNewUrlParser: true, useUnifiedTopology: true })

  .then(() => { console.log("connected"); })

  .catch(() => { console.log("error connecting"); });


// use the following code on any request that matches the specified mount path

app.use((req, res, next) => {

   console.log('This line is always called');

   res.setHeader('Access-Control-Allow-Origin', '*'); //can connect from any host

   res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS'); //allowable methods

   res.setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept');

   next();

});

app.get('/items', (req, res, next) => {

  //call mongoose method find (MongoDB db.Items.find())

  Items.find()

    //if data is returned, send data as a response 

    .then(data => res.status(200).json(data))

    //if error, send internal server error

    .catch(err => {

      console.log('Error: ${err}');

      res.status(500).json(err);

    });

});


  // parse application/x-www-form-urlencoded

app.use(bodyParser.urlencoded({ extended: false }))


// parse application/json

app.use(bodyParser.json())


// serve incoming post requests to /items

app.post('/items', (req, res, next) => {

// create a new item variable and save request’s fields 

const Items = new   items ({

  itemName: req.body.itemName,

  servings: req.body.servings

});

//send the document to the database 

Items.save()

  //in case of success

  .then(() => { console.log('Success');})

  //if error

  .catch(err => {console.log('Error:' + err);});

  });



//to use this middleware in other parts of the application

module.exports=app;


慕娘9325324
浏览 118回答 1
1回答

Qyouu

app.post('/items', (req, res, next) => {// Items already definedconst items = new Items({  itemName: req.body.itemName,  servings: req.body.servings});items.save()  //in case of success  .then(() => { console.log('Success');})  //if error  .catch(err => {console.log('Error:' + err);});  });Items 常量已被声明,而您试图重新声明它
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答