簡體   English   中英

在REST API中,如何使用Node.js和Express.js限制瀏覽器的URL訪問

[英]In REST API, How to restrict URL access from browser using Nodejs & Expressjs

我有一個MEAN堆棧應用程序,並使用Node.js和Express.js作為后端API。

假設我有一條“評論”路線,如下所示

/* GET /comments listing. */
router.get("/", function(req, res, next) {
    Comment.find(function(err, comments) {
        if (err) return next(err);
        res.json(comments);
    });
});

並像這樣在我的服務器中使用它:

var commentsRouter = require('./routes/comments');
...
app.use('/comments', commentsRouter);

我的問題是:有沒有一種方法可以防止用戶訪問瀏覽器中的http://mrUrl/comments並拒絕可能帶有403 Forbidden消息的請求,但同時JavaScript文件嘗試訪問相同的URL會收到一條內容消息(在示例中應該是res.json(comments);

同樣,有可能對所有路由啟用一次限制,而不是對每個路由啟用。

是的,您可以使用middleware

中間件是您可以在正在執行的主要功能之前或之后傳遞的功能(在這種情況下,是GET comments

函數位置的順序很重要,但是首先出現-首先執行,然后像這樣實現它:

app.use(myBrowsingRestrictionMiddlewareFunction) // Runs 

app.use('/comments', commentsRouter);

app.use('/account', accountRouter);

您也可以在route handler

app.post('/comments', myMakeSureDataIsAlrightFunction, myMainCreateCommentFunction, myAfterStatusWasSentToClientAndIWishToMakeAnotherInternalActionMiddleware);

接下來,屬性req, res, next將自動傳遞到函數中。

這意味着, myBrowsingRestrictionMiddlewareFunction收到它們,您可以像這樣使用它們:

export function myBrowsingRestrictionMiddlewareFunction(req, res, next) {
  if (req.headers['my-special-header']) {
     // custom header exists, then call next() to pass to the next function
     next();

  } else {

    res.sendStatus(403);      

  }
}

編輯

關於將中間件放在FS結構中的位置的擴展說明(個人建議):

我想做的是像這樣將路由器與app.js分開:

app.js

app.use('/', mainRouter);

router.js

const router = express.Router();

router.use(middlewareForAllRoutes);

router.use('/comments', commentsRouter);

router.use(middlewareForOnlyAnyRouteBelow);

router.use('/account', accountRouter);

router.use(middlewareThatWillBeFiredLast); // To activate this, remember to call next(); on the last function handler in your route.

commentsRou​​ter.js

const router = express.Router();

router.use(middlewareForAllRoutesONLYFORWithinAccountRoute);

route.get('/', middlewareOnlyForGETAccountRoute, getAccountFunction);

router.post('/', createAccount);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM