我正在构建我的第一个express.js应用程序,我遇到了第一个障碍。
我的设置非常简单。
app.js中的路线:
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/products', product.all);
app.post('/products', product.create);
route / product.js中的路由(控制器)
var Product = require('../models/product.js');
exports.create = function(req, res) {
new Product({ name: req.query.name, description: req.query.description }).save();
};
exports.all = function(req, res) {
Product.find(function(err, threads) {
if (err) {
res.send('There was an error: ' + err)
}
else {
res.send(threads)
}
});
}
models / product.js中的产品型号
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var productSchema = new Schema({
name: String,
description: String
});
module.exports = mongoose.model('Product', productSchema);
我尝试使用Postman(chrome扩展名)和Curl发送帖子请求。我注意到发送请求后似乎都挂起了,好像在等待响应,我不是http专家,但我认为帖子没有响应?但也许它会回应它是否成功?
我的样本请求:
http://0.0.0.0:3000/products?name=Cool
,http://0.0.0.0:3000/products?name=Cool%Product&description=Allo%there%Soldier!
发送帖子然后向http://0.0.0.0:3000/products
发送获取请求后,我得到了一系列对象,如下所示:
{
"_id": "52e8fe40b2b3976033ae1095",
"__v": 0
},
{
"_id": "52e8fe81b2b3976033ae1096",
"__v": 0
},
这些等于我发送的帖子请求数,向我表明服务器正在接收帖子并创建文档/文件,但实际上没有传递参数。
这里的一些帮助会很棒!
编辑:看起来上面的代码很好,我想我可能忘记在做了一些更改后重启我的节点服务器(Doh!),重启修复了问题
答案 0 :(得分:1)
类似于http请求生命周期,当然帖子有响应。
如果你的插件工作可能就像200,如果不是,那就是404!
您需要在create方法中发送回复:
exports.create = function(req, res) {
new Product({ name: req.query.name, description: req.query.description }).save();
res.send('saved');
};
答案 1 :(得分:0)
您的帖子需要回复。你可以做点什么
var newProduct = new Product({ name: req.query.name, description: req.query.description });
newProduct.save(function(err, entry) {
if(err) {
console.log(err);
res.send(500, { error: err.toString()});
}
else {
console.log('New product has been posted.');
res.send(JSON.stringify(entry));
}
});