每当我在8081/list_user
上提出请求时,都没有回应。当我打开localhost:8081
时,我得到了回复,但没有得到localhost:8081/list_user
。两个文件都在同一个文件夹中是否有任何问题。请检查此问题是什么问题。
// grab the things we need schema.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
console.log("Schema")
module.exports = User;
////////////Next file
var express = require('express');
var app = express();
var User = require('./schema');
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage",User);
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
var newUser = User({
name: 'Peter Quill',
});
// save the user
newUser.save(function(err) {
if (err) throw err;
res.send('User created!');
console.log('User created!');
});
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/find', function(req, res) {
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
console.log(users);
res.send(users)
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
答案 0 :(得分:0)
当我测试.save函数的方式时,我甚至无法收到错误消息。我所做的是添加与本地数据库(在模式文件)的连接以进行正确测试。
mongoose.connect(' mongodb的://本地主机/测试&#39);
为了做到这一点,首先你必须证明你有一个本地mongodb服务器正在运行(或者你可以只连接到在线服务器),mongoose.connect接收我的连接字符串作为参数(" test&# 34;是数据库名称,如果它不存在,它将自动创建)。我做的最后一件事是在创建用户时添加 new 。
var newUser = new User({
name: 'teste',
});