MEAN環境を構築し、mongoDBのデータをlocalhostにて表示させたい
localhost3000/apiで’これはサーバサイドスクリプトだよ’という表示は確認しています。
localhost3000/api/userでmongodbのデータを表示させたいのですが[]だけが表示されており、
データが反映されていないです。
勉強中でまだ写経の段階なのですが参考にしたサイトはこちらです
angular_cli 8.3.13 node 12.11.1. mongodb-community 4.2
mongodb
1> uset test_do 2> db.createCollection('users'); 3{ "ok" : 1 } 4> db.users.insert({last_name:'Suzuki',first_name:'ichiro'}); 5WriteResult({ "nInserted" : 1 }) 6> db.users.insert({last_name:'suzuki',first_name:'ziro'}); 7WriteResult({ "nInserted" : 1 }) 8> db.users.find() 9{ "_id" : ObjectId("5db02d3907ffa6fef2ea702e"), "last_name" : "Suzuki", "first_name" : "ichiro" } 10{ "_id" : ObjectId("5db02d7207ffa6fef2ea702f"), "last_name" : "suzuki", "first_name" : "ziro" } 11 12> 13 14
js
1//server.js 2 3const express = require('express'); 4const path = require('path'); 5const http = require('http'); 6 7//api.jsの読み込み 8const api = require('./server/routes/api'); 9 10//expressの初期化 11const app = express(); 12 13app.use(express.static(path.join(__dirname,'dist'))); 14 15app.use('/api',api); 16 17app.get('*',(req,res) => { 18 res.sendFile(path.join(__dirname,'dist/index.html')); 19}); 20 21//ポート設定 22const port = process.env.PORT || 3000; 23app.set('port',port); 24 25const server = http.createServer(app); 26 27server.listen(port,() => console.log('API running on localhost:${port}')); 28
js
1//api.js 2const express = require('express'); 3const router = express.Router(); 4const mongoose = require('mongoose'); 5 6//スキーマを定義 7var Schema = mongoose.Schema; 8var UserSchema = new Schema({ 9 first_name : String, 10 last_name : String 11}); 12 13mongoose.model('User',UserSchema); 14 15//MongoDBに接続 16mongoose.connect('mongodb://localhost/test_do'); 17 18var User = mongoose.model('User'); 19 20router.get('/',(req,res) => { 21 res.header('Content-Type','text/plain;charset=utf-8'); 22 res.send('これはサーバスクリプトだよ'); 23 24}); 25 26router.get('/user',(req,res) => { 27 //mongoからデータを取得 28 User.find({},function(err,docs){ 29 res.json(docs); 30 }); 31}); 32 33module.exports = router; 34
あなたの回答
tips
プレビュー