简体   繁体   中英

Use Express JS to block unwanted requests from the Client SIde

Consider the Express router :

const express = require("express");
const router = express.Router();
const DUMMY_PLACES = [
  {
    id: "p1",
    title: "Empire State Building",
    description: "One of the most famous sky scrapers in the world!",
    location: {
      lat: 40.7484474,
      lng: -73.9871516
    },
    address: "20 W 34th St, New York, NY 10001",
    creator: "u1"
  }
];


// @ http://localhost:5000/api/places/user/u1
router.get("/user/:uid", (req, res, next) => {
  const user_id = req.params.uid;
  const place = DUMMY_PLACES.find(p => {
    return p.creator === user_id;
  });

  return res.status(200).json({
    place
  });
});

module.exports = router;

And the Server :

const express = require("express");
const bodyParser = require("body-parser");
const app = express();

const placesRoutes = require("./routes/places-routes");
app.use("/api/places", placesRoutes);

const PORT = 5000;
app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

When clients hit the request http://localhost:5000/api/places/user/u1 , they get the dummy object ... however when hitting the request

http://localhost:5000/api/places/user

... it produces an empty object.

How can I return something like NOT ALLOWED instead of the empty object ?

Maybe you could check for the existence of a user_id and send an error response if there isn't one?

router.get('/user/:uid', (req, res, next) => {
  const user_id = req.params.uid

  if (!user_id) {
    return res.status(400).json({
      error: 'User ID required'
    })
  }

  const place = DUMMY_PLACES.find((p) => {
    return p.creator === user_id
  })

  return res.status(200).json({
    place
  })
})

The HTTP status codes are born to handle a lot of situation. In your case, there is a client error: the resource requested has not been found on the server (error 404).

In this case, your API can change in this way:

router.get("/user/:uid", (req, res, next) => {
  const user_id = req.params.uid;
  const place = DUMMY_PLACES.find(p => {
    return p.creator === user_id;
  });

  if (!place) { // if the place does not exist
    return res.status(404).json({
      message: 'The requested resource has not been found in the server.'
    });
  }

  return res.status(200).json({
    place
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM