- Install NodeJs, if you don't have it
- Execute below commands
mkdir myapi
cd myapi
npx express-generator --no-view
npm install cors
npm install helmet
npm install mongodb
npm install
Now, you can test your application. Execute the command npm start and navigate to the page http://localhost:3000 and then http://localhost:3000/users. Check the code. The most interesting files are users.js and app.js
- Create a file named book.js inside folder routes. Copy the code from the Book Example page.
- We have installed the modules cors and helmet, but we have to also add below lines to app.js
const helmet = require('helmet');
const cors = require('cors');
app.use(helmet());
app.use(cors());
- Because we have made a new route (book), we have to edit the file.
Add below lines to app.js
const bookRouter = require('./routes/book');
app.use('/book', bookRouter);
- And you can remove below lines from app.js
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
app.use('/', indexRouter);
app.use('/users', usersRouter);
- You can also remove files index.js and users.js from routes-folder
- Start the api with command npm start and type below urls to browser
- http://localhost:3000/book
- http://localhost:3000/book/Algebra
- The first one should return all books and the later books which name is Algebra.
- Use Postman to test all the methods in routes/book.js