Home > Software design >  express.js restfulApi, How to add an error message if the request to data.js is not found?
express.js restfulApi, How to add an error message if the request to data.js is not found?

Time:02-10

This is the code for the app.js file, it is for use as restful Api, I want to add a error message if the data in the array(data.js) is not found.

const express = require('express');
const data = require('./data');

// Initialize App
const app = express();

// Assign route
app.use('/api', (req, res, next) => {
    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];
        
      }
    
      return isValid;
    });
   
    res.send(filteredUsers);
  });

// Start server on PORT 5000
app.listen(8080, () => {
console.log('Server started!');
});

CodePudding user response:

you can send back a json as a response with 404 status and address the error, it would look something like this

if(!filteredUsers)
  res.status(404).send({
     error: "Data not found"
  })

or it can be a simple text

if(!filteredUsers.length)
   res.status(404).send("Data Not found")

CodePudding user response:

You can return error in restful api noed js like this:

if (!data) return res.status(404).send({ msg: 'data not found' })

actually in your code you should use it like this:

const data = require('./data');


app.use('/api', (req, res, next) => {
if (!data) return res.status(404).send({ msg: 'data not found' })

    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];
        
      }
    
      return isValid;
    });
   
    res.send(filteredUsers);
  });

good luck :)

  • Related