繁体   English   中英

Express.js:无法发布/用户错误

[英]Express.js : Cannot POST /users error

我正在尝试按照本教程学习MEAN堆栈,但是遇到了错误。 不幸的是,我无法找出我到底出了什么问题。

我试图通过创建用户来测试邮递员中的路由,但是我一直回想一下'Cannot POST / users'。

有人可以帮我从这里出去吗? 提前致谢!

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);

我相信这就是您的错误所在。

代替: module.exports = mongoose.model('scotch-user', UserSchema);

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

另外,请考虑将Express.js用于您的路线。 在Postman上进行测试时,请仔细检查您是否正在为MongoDB Schema输入所有“必需”部分。

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

您可以轻松地执行以下操作

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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM