Express.js:无法POST /用户错误

时间:2016-12-19 21:53:57

标签: javascript mongodb express postman

我正在尝试按照本教程学习MEAN堆栈,但我遇到了错误。不幸的是,我无法确切地发现我出错的地方。

我试图通过创建用户来测试Postman中的路线,但我一直在回来“不能POST /用户”。

任何人都可以帮助我吗?提前谢谢!

routes.js

// Dependencies
var mongoose        = require('mongoose');
var User            = require('./model.js');

// Opens App Routes
module.exports = function(app) {

    // GET Routes
    // --------------------------------------------------------
    // Retrieve records for all users in the db
    app.get('/users', function(req, res){

        // Uses Mongoose schema to run the search (empty conditions)
        var query = User.find({});
        query.exec(function(err, users){
            if(err)
                res.send(err);

            // If no errors are found, it responds with a JSON of all users
            res.json(users);
        });
    });

    // POST Routes
    // --------------------------------------------------------
    // Provides method for saving new users in the db
    app.post('/users', function(req, res){

        // Creates a new User based on the Mongoose schema and the post bo.dy
        var newuser = new User(req.body);

        // New User is saved in the db.
        newuser.save(function(err){
            if(err)
                res.send(err);

            // If no errors are found, it responds with a JSON of the new user
            res.json(req.body);
        });
    });
};

model.js

// Pulls Mongoose dependency for creating schemas
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Creates a User Schema. Defines how user data is stored to db
var UserSchema = new Schema({
    username        :   {type: String, required: true},
    gender          :   {type: String, required: true},
    age             :   {type: Number, required: true},
    favlang         :   {type: String, required: true},
    location        :   {type: [Number], required: true}, //[Long, Lat]
    htmlverified    :   String,
    created_at      :   {type: Date, default: Date.now},
    updated_at      :   {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
UserSchema.pre('save', function(next){
    now = new Date();
    this.updated_at = now;
    if(!this.created_at){
        this.created_at = now
    }
    next();
});

// Indexes this schema in 2dsphere format (critical for running proximity searches)
UserSchema.index({location: '2dsphere'});

// Exports the UserSchema for use elsewhere. Sets the MongoDB collection to be used as:
module.exports = mongoose.model('scotch-user', UserSchema);

server.js

// Dependencies
// -----------------------------------------------------
var express         = require('express');
var mongoose        = require('mongoose');
var port            = process.env.PORT || 3000;
var morgan          = require('morgan');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var app             = express();

// Express Configuration
// -----------------------------------------------------
// Sets the connection to MongoDB
mongoose.connect("mongodb://localhost/MeanMapApp");

// Logging and Parsing
app.use(express.static(__dirname + '/public'));                 // sets the static files location to public
app.use('/bower_components',  express.static(__dirname + '/bower_components')); // Use BowerComponents
app.use(morgan('dev'));                                         // log with Morgan
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.urlencoded({extended: true}));               // parse application/x-www-form-urlencoded
app.use(bodyParser.text());                                     // allows bodyParser to look at raw text
app.use(bodyParser.json({ type: 'application/vnd.api+json'}));  // parse application/vnd.api+json as json
app.use(methodOverride());

// Routes
// ------------------------------------------------------
require('./app/routes.js')(app);

// Listen
// -------------------------------------------------------
app.listen(port);
console.log('App listening on port ' + port);

2 个答案:

答案 0 :(得分:0)

我相信这是你的错误。

而不是: module.exports = mongoose.model('scotch-user', UserSchema);

尝试: module.exports = mongoose.model('User', UserSchema);

另外,请考虑使用Express.js作为路线。当您在Postman上进行测试时,请仔细检查您是否正在输入所有" required" MongoDB Schema的部分。

答案 1 :(得分:0)

我刚刚复制了你的脚本,我完全没有问题! 确保你在邮递员中使用正确的方法和路线 小提示:Mongoose处理它自己的架构,因此无需导出它们。

您可以轻松执行以下操作

app.js

// Dependencies
// -----------------------------------------------------
var express         = require('express');
var mongoose        = require('mongoose');
var port            = process.env.PORT || 3000;
var morgan          = require('morgan');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var app             = express();

// Load all models
require('./app/model');


// Express Configuration

model.js

// remove module.exports in the last line 
mongoose.model('User', UserSchema);

routes.js

// Dependencies
var mongoose        = require('mongoose');
var User            = mongoose.model('User');