2016-06-21 1 views
1

なぜマングースがexpressjsサイトをクラッシュさせますか?以下はExpressjs + Mongoose - このウェブページはありませんか?

私のコードです:

var express = require('express'); 
var mongoose = require('mongoose'); 
var app = express(); 

// Connect to mongodb 
mongoose.connect("mongodb://localhost/testdb", function(err) { 
    if (err) throw err; 
    console.log("Successfully connected to mongodb"); 

    // Start the application after the database connection is ready 
    app.listen(3000); 
    console.log("Listening on port 3000"); 
}); 

// With Mongoose, everything is derived from a Schema. Let's get a reference to it and define our users. 
var userSchema = mongoose.Schema({ 
    name: String, 
    username: { type: String, required: true, unique: true }, 
    password: { type: String, required: true }, 
    admin: Boolean, 
    location: String, 
    meta: { 
     age: Number, 
     website: String 
    }, 
    created_at: Date, 
    updated_at: Date 
}); 

// The next step is compiling our schema into a Model. 
var User = mongoose.model('User', userSchema); 

// Set route. 
app.get("/", function(req, res) { 

    // We can access all of the user documents through our User model. 
    User.find(function (err, users) { 
    if (err) return console.error(err); 
    console.log(users); 
    }) 
}); 

私はブラウザ上でこれを取得する:

This webpage is not available 

しかし、私の端末では、私は結果を得る:

Successfully connected to mongodb 
Listening on port 3000 

[ { _id: 57682f69feaf405c51fdf144, 
    username: 'testuser1', 
    email: '[email protected]' }, 
    { _id: 57683009feaf405c51fdf145, 
    username: 'testuser2', 
    email: '[email protected]' }, 
    { _id: 57683009feaf405c51fdf146, 
    username: 'testuser3', 
    email: '[email protected]' }] 

私が持っているものすべてのアイデア逃した?

答えて

2

問題は、リクエストハンドラのレスポンスオブジェクトに何も記述していないことです。したがって、ブラウザはリクエストの完了を待ってからタイムアウトになります。あなたのapp.get()では、次のように応答を更新することができます:

// Set route. 
app.get("/", function(req, res) { 

    // We can access all of the user documents through our User model. 
    User.find(function (err, users) { 
    if (err) { 
     console.error(err); 
     // some simple error handling, maybe form a proper error object for response. 
     res.status(500).json(err); 
    } 
    console.log(users); 
    res.status(200).json(users); // setting the object as json response 

    //OR 

    // res.end(); if you don't want to send anything to the client 
    }) 
}); 

または類似のものです。

詳細については、Expressドキュメントを参照してください。http://expressjs.com/en/api.html#res

+0

Aww。そうですか!助けてくれてありがとう! – laukok

+0

うれしい私は助けることができました! :) –

+0

エラーが発生した場合は、応答も送信する必要があります。 – robertklep

関連する問題