使用Express JS阻止来自客户端SIde的不需要的请求

时间:2020-02-22 14:05:15

标签: javascript node.js express

考虑Express路由器:

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;

服务器:

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}`);
});

当客户点击请求http://localhost:5000/api/places/user/u1时,他们会得到虚拟对象...但是,当点击请求时

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

...它产生一个空对象。

如何返回类似NOT ALLOWED的内容而不是空对象?

2 个答案:

答案 0 :(得分:1)

也许您可以检查是否存在一个user_id,如果没有,则发送错误响应?

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
  })
})

答案 1 :(得分:1)

HTTP status codes的诞生是为了应对许多情况。您的情况是客户端错误:在服务器上找不到请求的资源(错误404)。

在这种情况下,您的API可以通过以下方式更改:

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
  });
});