Bitnami MEAN STACKを実行するEC2インスタンスがあります。私がしたいのは、私のAPIのエンドポイントを呼び出すようにmongoとNodeを設定することです。 app.js
というファイルを作成しました。そこで、mongoに接続するAPIを実装しました。アクセスAPIエンドポイントEC2 +ノード+ ExpressJS
疑いの余地はありません:どのようにmongoに接続しますか?私はEC2インスタンスの中で実行しているので、私はlocalhostでmongoホストを残すべきですか?
mongoose.connect('mongodb://localhost/mydb');
エンドポイントにアクセスするためのURLはどれですか?私のEC2のインスタンスでは、私は
node app.js
を実行していますので、実行しています...どのブラウザでも行くことができ、 `.../api/users 'のようなURLはどこですか?
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私はあなたが言っていることを理解していません。私はこのコメントがあなたの質問または私の答えにどのように関係しているかわかりません。 –