Reputation: 103
The route is not working. I been looking for the cause and I can't find where the problem is. I keep on getting 404 error on postman with the server running.
Here is my 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, {useNewUrlParser: true} )
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
//Routes
app.use ('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Here is the file containing the routes. Is located at /routes/api
const express = require('express');
const router = express.Router();
// Item Model
const Item = require('../../models/Item');
// @route GET api/items
// @desc Get All Items
// @access Public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items));
});
module.exports = router;
File models/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);
Upvotes: 1
Views: 1025
Reputation: 323
Please understand the basic routes first. Here is https://expressjs.com/en/guide/routing.html
When you run app like that http://localhost:3000 app is runnin exactly on this url. If you route somthing else like that "api/items" this means that http://localhost:3000api/items. So create any route firstly add a '/' and then it looks like http://localhost:3000/api/items
Upvotes: 0
Reputation: 13699
404 status : Route Not found , the url you are trying that is not found
in your app js , add slash /
before api
app.use('/api/items', items);
url will be :
http://localhost:5000/api/items
Upvotes: 2