我正在使用Node JS和MongoDb,我试图从MongoDb获取数据,但是我得到了GET / 404错误。但是我可以成功连接到MongoDB。
这是我的Server.js
// set up ======================================================================
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8000; // set the port
var database = require('./config/database'); // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var messageId = {};
// configuration ===============================================================
// Connect to DB
mongoose.connect(database.remoteUrl)
mongoose.connection.on('error', function(e) {
console.log('Can not connect Error:>>',e);
process.exit();
});
mongoose.connection.once('open', function(d) {
console.log("Successfully connected to the database");
})
//app.use(express.static('./public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
io.set('origins', '*:*');
http = require('http'),
server = http.createServer(function (req, res) {
//res.writeHead(200,{'content-type':'text/plain'});
// res.write("Sever On");
// res.end();
}),
io = io.listen(server);
io.on('connection', function (socket) {
console.log('User Connected -- Server Online');
socket.on('message', function (msg,msgId) {
io.emit('message', "Hello");
console.log("message from client:", msg);
setInterval(function(){
io.emit("messageStatus",msgId);
},500)
});
});
app.use(require('./app/routes.js'));
app.listen(port);
//server.listen(port);
console.log("App listening on port " + port);
启动服务器后,我总能成功连接。我目前正在localhost:8000
上运行服务器这是我的config / database.js,我使用AWS来托管我的MongoDB
module.exports = {
remoteUrl : 'mongodb://username:password@ec2-22-127-21-183.ap-south-1.compute.amazonaws.com:27017/testdb'
};
我已经基于MongoDB创建了一个Schema,将其命名为userprofile.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProfileSchema = new Schema({
id:{
type:String,
required:true
},
FirstName:{
type:String,
required:true
},
LastName:{
type:String,
required:true
},
EmailID:{
type:String,
required:true
},
Phone:{
type:Number,
required:true
},
Address1:{
type:String,
required:true
},
Address2:{
type:String,
required:true
},
PinCode:{
type:Number,
required:true
},
Gender:{
type:String,
required:true
},
ProfilePic:{
type:String,
required:true
},
IDproof:{
type:String,
required:true
},
UserName:{
type:String,
required:true
},
Password:{
type:String,
required:true
},
Dob:{
type:Number,
required:true
},
City:{
type:String,
required:true
},
State:{
type:String,
required:true
},
HighestEducation:{
type:String,
required:true
}
})
module.exports = mongoose.model('UserProfile',ProfileSchema);
这是我的route.js
var express = require('express')
var app = module.exports = express.Router();
var UserProfile = require('./models/UserProfile');
app.get('/User', function (req, res) {
UserProfile.find(function (err, profile) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
return res.json({"success":false,"msg":err})
console.log(err);
}
res.status(200).send({"success":true,"result":profile})
});
});
在Mongo DB中,我有一个名为testdb的数据库 我有一个名为User的集合 这是表中条目之一的样本
db.User.find().pretty()
{
"_id" : ObjectId("5a83d1400d47870303228bfa"),
"FirstName" : "Jazz",
"LastName" : "Ben",
"EmailID" : "abc@gmail.com",
"Phone" : 7654329878,
"Address1" : "Golden Tulip Est",
"Address2" : "Earth",
"PinCode" : 500084,
"Gender" : "WhoCares",
"ProfilePic" : "hugyft.in",
"IDproof" : "hugyc.in",
"UserName" : "Jazz",
"Password" : "1736127",
"Dob" : 1071985,
"City" : "TheBest",
"State" : "Solid",
"HighestEducation" : "PHD"
}
请帮助我undertsand我哪里出错了。
答案 0 :(得分:0)
我意识到我的错误,应该是localhost:8000/User
用户是数据库中的我的集合。