MERN堆栈,REST API邮递员,无法获取/

时间:2018-09-04 08:11:28

标签: node.js mongodb rest api mern

我正在尝试使用Postman和MERN堆栈创建一个简单的REST api

我有以下文件

server.js,Item.js,item.js,keys.js

server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const items = require('./routes/api/items');

const app = express();

// BodyParser Middleware
app.use(bodyParser.json());

// DB Config
const db = require('./config/keys').mongoURI;

//Connect to Mongo
mongoose
    .connect(db)
    .then(() => console.log('MongoDB Connected'))
    .catch(err => console.log(err));


app.use('./api/items', items);

const port = process.env.PORT || 5000;

app.listen(port, () => console.log('server started'));

Item.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const ItemSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }
});

module.exports = Item = mongoose.model('item', ItemSchema);

items.js

const express = require('express');
const router = express.Router();

const Item = require('../../models/Item');

router.get('/', (req, res) => {
    Item.find()
        .sort({ date: -1 })
        .then(items => res.json(items))
});

module.exports = router;

keys.js

module.exports = {
    mongoURI: 'mongodb://tset:tset123@ds241012.mlab.com:41012/mern_shopping'
}   

服务器连接并连接到数据库-我获得了控制台日志。

在邮递员中,如果我尝试使用GET和网址http://localhost:5000,我会得到

Cannot GET /

如果我尝试http://localhost:5000/api/items我会得到

Cannot GET /api/items

2 个答案:

答案 0 :(得分:2)

更改此

app.use('./api/items', items);

app.use('/api/items', items);

答案 1 :(得分:0)

,对于http://localhost:5000,您必须使用

定义的根
app.get('/', function (req, res) {})