ExpressJS POST方法请求问题

时间:2014-08-29 00:58:06

标签: javascript node.js express

我遇到了一个问题,我试图通过Postman运行POST请求,我收到了很长时间的加载请求,然后收到Could not get any response消息。终端中没有出现错误。这是我保存POST的方式吗?特别关注我/博客路线。

server.js

//Load express
var express = require('express');
var app = express();
var router = express.Router(); // get an instance of the router
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
// configure app to use bodyParser()
// get data from a POST method
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

var port = process.env.PORT || 8080; // set the port


var blogDB = require('./config/blogDB.js');

var Blogpost = require('./app/models/blogModel');

app.set('view engine', 'ejs'); // set ejs as the view engine

app.use(express.static(__dirname + '/public')); // set the public directory



var routes = require('./app/routes');
// use routes.js
app.use(routes);


app.listen(port);
console.log('magic is happening on port' + port);

blogModel.js:

var mongoose    = require('mongoose');
var Schema      = mongoose.Schema;

var BlogPostSchema  = new Schema({
        title : String,
        body : String,
        date_created : Date
});

module.exports = mongoose.model('Blogpost', BlogPostSchema);

routes.js:

var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');

//index
    router.route('/')
    .get(function(req, res) {
    var drinks = [
            {   name: 'Bloody Mary', drunkness: 3 },
            {   name: 'Martini', drunkness: 5 },
            {   name: 'Scotch', drunkness: 10}
        ];

        var tagline = "Lets do this.";

        res.render('pages/index', {
            drinks: drinks,
            tagline: tagline
        });
    });

//blog
    router.route('/blog') 

        .get(function(req, res) {
            res.send('This is the blog page');
        })

        .post(function(req, res) {

            var blogpost = new Blogpost(); // create a new instance of a Blogpost model
            blogpost.title = req.body.name; // set the blog title
            blogpost.body = req.body.body; // set the blog content
            blogpost.date_created = Date.now();

            blogpost.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Blog created.' });
            });

        });




//about
    router.get('/about', function(req, res) {
            res.render('pages/about');
    });


module.exports = router;

1 个答案:

答案 0 :(得分:0)

问题是我没有为Mongo数据库设置用户。基本上它无法访问我正在使用的数据库的用户/ pw。一旦我创建了一个匹配我的网址中包含的用户/ pw的用户,那么我就能获得一个成功的帖子。