我有運行Bitnami MEAN堆棧EC2實例。我想要做的就是設置mongo和Node,以便調用我的API的端點。我寫了我的app.js
文件,我已經實現了一個連接到mongo的API。訪問API端點EC2 +節點+ ExpressJS
我現在懷疑的是:如何連接到mongo?當我在EC2實例中運行它時,是否應該使用localhost離開mongo主機?
mongoose.connect('mongodb://localhost/mydb');
這是訪問我的端點的網址是什麼?在我的EC2實例中,我運行了
node app.js
,所以現在它正在運行...哪個URL可以在任何瀏覽器中使用,並且像`.../api/users'一樣?
api.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10;
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
app.use(express.static(__dirname));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
mongoose.connect('mongodb://localhost/mydb');
app.get('/', function(req, res){
res.redirect('/index.html');
});
app.all("/api/*", function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
return next();
});
app.all("/api/*", function(req, res, next) {
if (req.method.toLowerCase() !== "options") {
return next();
}
return res.send(204);
});
// define model =================
var UserSchema = new Schema({
email: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
});
var User = mongoose.model('User', UserSchema);
// api ---------------------------------------------------------------------
// get all todos
/* USERS API */
app.get('/api/users', function(req, res) {
// use mongoose to get all todos in the database
User.find(function(err, users) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(users); // return all todos in JSON format
});
});
app.listen(process.env.PORT || 5000)
@Rüménok我不明白你在說什麼。我不明白這個評論與你的問題或我的答案有關。 –