0
我遇到了一個問題,我試圖通過Postman運行POST請求,並且我得到一個很長時間的加載請求,然後是一條Could not get any response
消息。沒有出現在終端的錯誤。這是我保存POST的方式嗎?具體看我的/博客路線。ExpressJS 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;
您是否嘗試在回調函數中向控制檯輸出內容?是否定義了「blogpost」? 'save'方法是否成功? – 2014-08-29 08:50:31
@WaldoJeffers'blogpost'在'router.route('/ blog')'的post方法中定義。當我在Postman中運行一個post請求時,我得到一個永不停息的長時間加載...通知。沒有發佈說明「Blog created.'的消息,我用它作爲成功消息。這可能是我如何設置mongodb配置的問題嗎? – cphill 2014-08-29 20:43:01