構築中のAngular/Node/Expressアプリケーションで接続しようとしているBitnami Lightsail MEANスタックインスタンスにMongoデータベースを設定しました。ローカルマシン(https://docs.bitnami.com/aws/infrastructure/mean/)からSSHポート転送を接続して作成する方法に関する指示に従ってきました。エクスプレスルータを使用してMongoDBに返されたデータがありません
私はMongoデータベースでMEAN Lightsailインスタンスに設定されたRockMongoにアクセスできるlocalhost:8888にアクセスできます。つまり、ローカルマシンからサーバーに接続するための構成は問題ないと思います。
node server
を実行し、私のapi GETメソッドのURL(http://localhost:3000/api/numbers)に移動すると、データベースへの接続時にエラーが発生しません。代わりに、私は基本的にデータの空の配列で、次の応答を取得:ここ
{"status":200,"data":[],"message":null}
は私のapi.jsファイルのコードです:
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
// Connect
const connection = (closure) => {
return MongoClient.connect('mongodb://localhost:27017/sakDB', (err, db) => {
if (err) {
return console.log(err);
}
closure(db);
});
};
// Error handling
const sendError = (err, res) => {
response.status = 501;
response.message = typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
// Response handling
let response = {
status: 200,
data: [],
message: null
};
// Get numbers
router.get('/numbers', (req, res) => {
connection((db) => {
db.collection('numbers')
.find()
.toArray()
.then((numbers) => {
response.data = numbers;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
module.exports = router;
そして、私のrouter.jsためのコードファイル:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
const api = require('./server/routes/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port,() => console.log(`Running on localhost:${port}`));
これは、MEAN LightsailインスタンスのMongoDBの設定上の問題であると考え始めています。私はMongoDBのシェルでdb.numbers.find()
を実行しようとすると、私は次のエラーを取得する:
MongoDB server version: 3.4.7
> db.numbers.find()
Error: error: {
"ok" : 0,
"errmsg" : "not authorized on sakDB to execute command { find: \"numbers\", filter: {} }",
"code" : 13,
"codeName" : "Unauthorized"
}
私はコレクションのデータを見つけるために作成したユーザーにmongo sakDB -u admin -p
としてログインする必要があります。
私は、接続文字列mongodb://admin:[email protected]:27017/sakDB
にこれらの資格情報を追加しようとすると、私は別の認証エラーが表示されます。
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
おそらくライブラリに問題があります。このスタートガイドを確認しましたか? https://docs.bitnami.com/google/infrastructure/mean/#how-can-i-get-started-with-mean –