2014-01-27 75 views
0

我使用Mongoose和Express.js来制作简单的待办事项列表应用程序。当我从表单发帖时,我想保存列表项并在下一页上显示一条消息。 (稍后将重定向来代替)而不是显示的消息,Chrome的页面将停止,直到它最后说ERR_EMPTY_RESPONSE保存Mongoose模型时

No data received
Unable to load the webpage because the server sent no data.
Reload this webpage.
Press the reload button to resubmit the data needed to load the page.
Error code: ERR_EMPTY_RESPONSE

火狐说The connection to the server was reset while the page was loading.

我的路线是这样的:

exports.post = function(req, res) { 
    var Item = require('../models/Item') 

    new Item({ 
     content: req.body.content 
    }).save(function(){ 
     res.send('item saved') 
    }) 
} 

我也试过:

var item = new Item({ 
    content: req.body.content 
}) 

item.save(function(){ 
    res.send('item saved') 
}) 

它做同样的事情。

我的模型看起来是这样的:

var mongoose = require('mongoose') 

var ItemSchema = new mongoose.Schema({ 
    content: String 
}) 

var Item = mongoose.model('Item', ItemSchema) 
module.exports = Item 

我如何在保存函数来执行?

编辑: 这里是客户端代码:

layout.jade

doctype html 
html 
    head 
    meta(charset='utf-8') 
    title Listocracy 
    body 
    block content 

index.jade

extends layout 

block content 
    h1 Listocracy 

    form(method='post', action='/item') 
    input(type='text', name='content') 
    button(type='submit') Add Item 

如果我拉出来res.send的保存功能会打印文本就像它应该的。我认为问题在于保存功能。

+0

我忘了连接到MongoDB的。 – Eva

回答

2

试试这个方法:

(new Item({ 
    content: req.body.content 
})).save(function(){ 
    res.send('item saved') 
}); 

更好的方式:

var item = new Item({ 
    content: req.body.content 
}); 

item.save(function(err){ 
    if(!err) 
     res.send('item saved') 
    // else log and send error message 
}); 
+0

我得到'500 TypeError:undefined不是一个函数'不知道他们指的是哪个函数,因为所有东西都是链接的,但是将它拆分会带来ERR_EMPTY_RESPONSE问题。 – Eva

+0

将第二个更改为'(item).save(...)'。它现在说'500 TypeError:对象不是该行的函数。它是否读取'(item)'作为函数? – Eva

+0

@Eva查看编辑答案 – karaxuna