服务器未运行

时间:2019-07-29 07:08:14

标签: express

import express from 'express'; import mongodb from 'mongodb'; const app = express(); const dburl = 'mogodb://localhost/crudwithredux';

mongodb.MongoClient.connect(dburl,{useNewUrlParser:true},function(err,db){app.get('/ api / games',(req,res)=> {{db.collection('games' ).find({}).toArray((err,games)=> {res.json({games});});});

app.listen(8080,()=> console.log('服务器正在本地主机上运行:8080')); });

1 个答案:

答案 0 :(得分:0)

您尚未为mongodb服务器指定端口。请在连接URL中指定该端口。

第二,您不应在mongo connect函数内编写api端点,而应获取数据库对象并在各处重用。

以下是正确的处理方式:

import express from 'express';
import mongodb from 'mongodb';
const app = express();
const dburl = 'mogodb://localhost:27017/crudwithredux';
var db;

mongodb.MongoClient.connect(dburl, { useNewUrlParser: true }, function (err,database) {

   db = database;
   app.listen(8080, () => console.log('Server is running on localhost:8080'));
});

app.get('/api/games', (req, res) => {
        db.collection('games').find({}).toArray((err, games) => {
            res.json({ games });
        });
    });