REST API with Express.js
Express-api for MongoDB
  1. Install NodeJs, if you don't have it
  2. 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

  3. Create a file named book.js inside folder routes. Copy the code from the Book Example page.
  4. 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());
    
  5. 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);
    
  6. 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);
    
  7. You can also remove files index.js and users.js from routes-folder
  8. Start the api with command npm start and type below urls to browser
    • http://localhost:3000/book
    • http://localhost:3000/book/Algebra
  9. The first one should return all books and the later books which name is Algebra.
  10. Use Postman to test all the methods in routes/book.js



Toggle Menu