所以我在Node.js / Express / MongoDB中构建了一个应用程序,我遵循了一些teamtreehouse教程,但这是通过shell而不是远程服务器运行Node.js。我已经在数字海洋服务器上设置了Node.js和MongoDB,它说我能够连接但是我已经尝试过差异点来为我的api命中。
现在我的应用程序从http://joshuaericbenner.me/projects/sideprojects/LinkedInApp/public/
运行我的文件结构如下:
LinkedInAppp
-> public -> index.html
-> src
-> api -> index.js (where the api calls exist)
-> database.js
所以我的问题是,我不应该点击http://joshuaericbenner.me/projects/sideprojects/LinkedInApp/api/users的端点并获得回复吗?
目前,当我在Postman尝试时,我得到了回复:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /projects/sideprojects/LinkedInApp/api/users was not found on this server.</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at joshuaericbenner.me Port 80</address>
</body>
MongoDB连接(database.js):
'use strict';
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/LinkedInUsers',function(err){
if(err){
console.log("Failed to connect to mongodb");
}
else{
console.log("Successfully connected to mongodb");
}
});
来自我服务器shell的Mongo输出:
MongoDB shell version: 2.6.10
connecting to: test
> show dbs
LinkedInUsers 0.078GB
admin (empty)
local 0.078GB
test 0.078GB
> use LinkedInUsers
switched to db LinkedInUsers
> db.post.find()
{ "_id" : ObjectId("5810e578059f3fc430a6089b"), "formattedName" : "jb" }
我运行Node.js应用程序时输出Node.js:
root@joshuaericbenner:/var/www/html/projects/sideprojects/LinkedInApp# nodejs src/app.js
Now running on port 8080
Successfully connected to mongodb
Express API(如上所述index.js):
'use strict';
var express = require('express');
var User = require('../models/user');
var router = express.Router();
//Get All Users
router.get('/users', function (req, res){
User.find({}, function(err, users){
if(err){
res.status(500 ).json({message: err.message});
}
res.json({users: users});
});
} );
App.js &#39;使用严格的&#39;;
var express = require('express');
var parser = require('body-parser');
var router = require('./api');
var app = express();
require('./database');
require('./seed');
app.use(parser.json());
app.use('/', express.static('public'));
app.use('/api', router);
app.listen(8080, function (){
console.log("Now running on port 8080");
});
用户模型:
'use strict';
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
formattedName: String,
id: String,
location: {
country: {
code: String
},
name: String
},
positions:
{
values:
[
{
company: {
id: Number,
location: {
name: String
}
},
location: {
name: String
},
id: Number,
isCurrent: Boolean,
summary: String,
title: String
}
]
},
publicProfileUrl: String
});
var model = mongoose.model('User', userSchema);
module.exports = model;
答案 0 :(得分:0)
问题出在您的路线上。当您的路线配置为/api/users
时,您正在拨打users
。
router.get('/api/users', function (req, res){
User.find({}, function(err, users){
if(err){
res.status(500 ).json({message: err.message});
}
res.json({users: users});
});
} );