Node.js Expressjs+;猫鼬-此网页不可用?
为什么猫鼬会破坏expressjs网站 下面是我的代码:Node.js Expressjs+;猫鼬-此网页不可用?,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,为什么猫鼬会破坏expressjs网站 下面是我的代码: 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("Suc
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: 'testuser1@testdomain.com' },
{ _id: 57683009feaf405c51fdf145,
username: 'testuser2',
email: 'testuser2@testdomain.com' },
{ _id: 57683009feaf405c51fdf146,
username: 'testuser3',
email: 'testuser3@testdomain.com' }]
您知道我遗漏了什么吗?问题是您没有在请求处理程序的响应对象中写入任何内容。因此,浏览器会一直等待请求完成,并以超时结束。在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文档:很高兴能为您提供帮助!:)当发生错误时,也应该发送响应。是的,我同意罗伯特的观点。编辑。