2014-01-27 78 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