Reputation: 11201
I am trying to create a simple rest endpoint using node.js. I am following the tutorial https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
the folder structure is notable/app/routes/ and the routes folder contains the index.js and note_routes.js files
I am able to run the command npm run dev
, and the output shown is:
> [email protected] dev /Users/tejanandamuri/Desktop/notable
> nodemon server.js
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
We are live on 8000
after this. in the postman, when I try to call the http://localhost:8000/notes, it is returning 404 error with the response body Cannot POST /notes
Here are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});
index.js:
// routes/index.js
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
noteRoutes(app, db);
// Other route groups could go here, in the future
};
note_routes.js
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
// You'll create your note here.
res.send('Hello')
});
};
package.json:
{
"name": "notable",
"version": "1.0.0",
"description": "my first rest api",
"main": "server.js",
"dependencies": {
"body-parser": "^1.17.2",
"express": "^4.15.3",
"mongodb": "^2.2.28"
},
"devDependencies": {
"nodemon": "^1.11.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js"
},
"author": "venkata",
"license": "ISC"
}
Upvotes: 1
Views: 1458
Reputation: 913
Change line 6 in server.js to require('./routes/note_routes')(app, {});
This assumes your file tree looks something like this:
.
+--/node_modules // this contains a ton of sub-folders
+--/routes
+ +--index.js
+ +--note_routes.js
+--package.json
+--server.js
Upvotes: 1