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);
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
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
Related
I have a route to create a category and when I try to run it in postman it returns an error saying, "Cannot POST /api/category"
I have tried to run through my code again and again but I cannot see where is the problem.
Thank for your help in advance
My schema:
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
categoryName: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Categories = mongoose.model("category", CategorySchema);
My route:
const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const { check, validationResult } = require("express-validator");
const Category = require("../../models/Category");
// #route POST api/category
// #desc Create or update users category
// #access Private
router.post(
"/",
[auth, [check("categoryName", "Category name is required").not().isEmpty()]],
async (req, res) => {
console.log(categoryName);
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
}
);
module.exports = router;
this is the way my code is organized
Ok thanks to Molda I found the problem.
I was missing my route definition in my server.js file.
All good now, thank you for your help.
const express = require("express");
const connectDB = require("./config/db");
const app = express();
//Connect DB
connectDB();
// Init Middleware
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send("API Running"));
// Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/category", require("./routes/api/category"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
This is an express server that interacts with a mongoDb server using mongoose.Here I want to search for a specific entry with a given name instead of using findbyid function in the /getCollege/:name route.
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// app.use(parser);
mongoose.connect('mongodb+srv://swapnil:abc#cluster0.ma46p.mongodb.net/db?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('connected to db') })
//
app.get('/', (req, res) => {
res.send('We are home');
})
app.get('/getCollege/:name',async (req,res) =>{
})
app.listen(3000);
Parameters variables such as :name are available through req.params, on your case: req.params.name. After getting the value you would something like:
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// your code
app.get('/getCollege/:name',async (req, res) =>{
try {
const document = await College.findOne({ name: req.params.name });
res.json(document);
} catch(error) {
// Handle the error here.
console.log(error);
}
});
// your code
Take a look at these reading materials as well:
1 - http://expressjs.com/en/guide/routing.html
2 - https://medium.com/weekly-webtips/9-best-practices-for-rest-api-design-7fb0b462099b
I've created a very simple API in NodeJs. Here is the code:
const Post = require('../models/article');
...
router.post('/contribute', (req, res) => {
console.log('Pushing new article');
let userPost = req.body;
let post = new Post(userPost);
post.save((error, registeredPost) => {
if (error) {
console.log(error);
} else {
res.status(200).send(registeredPost);
}
})
})
...
module.exports = router;
The structure of a Post is this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const articleSchema = new Schema({
articleid: String,
title: String,
content: String,
date: String,
contributor: String,
upvotes: Number,
upvoters: [String],
downvotes: Number,
downvoters: [String]
})
module.exports = mongoose.model('article', articleSchema, 'articles');
Here is server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes/api');
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
app.use('/api', api);
app.get('/', function(req, res) {
res.send('Server is up and running!');
})
app.listen((3000), function() {
console.log('Server listening on heroku environment port');
});
Ideally the data should come from an angular form/template but before pushing the code I wanted to test this on Postman. Here is the screenshot:
I'm getting:
Cannot POST /contribute
Please point out my mistake.
Because you are using:
app.use('/api', api)
So, make sure to use this endpoint:
localhost:3000/api/contribute
And now, it's will working fine.
I didn't notice that I'm hitting the wrong URL.
Wrong:
localhost:3000/contribute
Correct:
localhost:3000/api/contribute
This is working absolutely fine now and I'm getting correct json response from the server also.
I m testing a simple Get api with postman, but i am getting "cannot GET".
server.js (in the root folder)
```const express = require('express');
const mongoose = require('mongoose');
const items = require('./routes/api/items');
const app = express();
//body Parser middleware
app.use(express.json());
//Db config
const db = require('./config/keys').mongoURI;
//const db = "mongodb+srv://gkmm:123123123#cluster0-bo4ln.mongodb.net/test?retryWrites=true&w=majority"
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser:true, useUnifiedTopology: true})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server started on port ${port}`));
//Use routes
app.use('./routes/api/items.js', items);```
routes(root folder)/api/items.js
```const express = require('express')
const router = express.Router();
//Item Model
const Item = require('../../models/Item')
//#route GET api/items
//#des Get AAll Items
//access public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1})
.then(items => res.json(items));
});
module.exports = router; ```
Running into this error while trying to test my API, i checked my paths are correct, my database is connected. but i have no idea why is it returning 404 not found.
After looking through your code, # the line which you ask app to use your routes
//Use routes
/* You are telling the route to go through e.g. <yoururl>/./routes/api/items.js/
in order to reach your GET in items.js
*/
app.use('./routes/api/items.js', items);```
To resolve this issue you can edit your app.use to
app.use('/test', items) // test is just an example, you can change it to other keywords
Then to access your items GET route use "/test/"
Shouldn't app.use('./routes/api/items.js', items); be app.use('/api/items', items); ?
I'm trying to create a simple REST api using Postman and the MERN stack
I have the following files
server.js, Item.js, items.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'
}
The server connects and connects to the DB - I get the console logs.
In postman if I try the GET and the url http://localhost:5000 I get
Cannot GET /
If I try http://localhost:5000/api/items I get
Cannot GET /api/items
Change this
app.use('./api/items', items);
to
app.use('/api/items', items);
and for http://localhost:5000 , the root you have to define with
app.get('/', function (req, res) {})