为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕娘9325324 2022-06-05 11:06:57
尝试在表单上提交数据时,网络服务器给我一个错误,说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 schemaconst 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 pathapp.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-urlencodedapp.use(bodyParser.urlencoded({ extended: false }))// parse application/jsonapp.use(bodyParser.json())// serve incoming post requests to /itemsapp.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 applicationmodule.exports=app;
查看完整描述

1 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

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


// Items already defined

const 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 常量已被声明,而您试图重新声明它


查看完整回答
反对 回复 2022-06-05
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信