在使用node.js和express构建CRUD Api时,我遇到了一个小问题。
当我发布到我的API时,我得到" ReferenceError:Phone未定义"
// server.js
//基础设置 // ================================================ =============================
//调用我们需要的包
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var phone = require('./models/phone');
var mongoose = require('mongoose');
mongoose.connect('mongodb://<userID>:<pass>@apollo.modulusmongo.net:27017/ugygY5qe');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
router.use(function(req,res,next){
console.log('Something is happening');
next();
});
router.route('/phones').post(function(req, res){
var phone = new Phone();
phone.name = req.body.name;
phone.save(function(err){
if(err){
res.send(err);
}
res.json({message: 'Phone Create'});
});
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
这是我的架构文件。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var phoneSchema = new Schema({
name: String
});
module.exports = mongoose.model('Phone', phoneSchema);
我不确定错误在哪里。我已经咨询过mongoose文档,搜索但仍然无法正常工作。
答案 0 :(得分:0)
只是一个错字!检查第4行。
var Phone = require('./models/phone');