Access request headers from beforeSave Model Hook

后端 未结 5 878
执笔经年
执笔经年 2021-01-18 05:07

How can i access the details of the user who raise the request from a Model Hook

Comment.beforeSave =  function(next,com) {
//Want to add 2 more properties          


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 05:59

    I solved this by adding the middleware for body parsing. In the middleware.js I wrote the following code:

    ...
    "parse": {
       "body-parser#json": {},
       "body-parser#urlencoded": {"params": { "extended": true }}
    },
    ...
    

    Also, in the server.js I added the require for the body parser and multer:

    var loopback = require('loopback');
    ...
    var bodyParser = require('body-parser');
    var multer = require('multer');
    ...
    
    app.use(bodyParser.json()); // application/json
    app.use(bodyParser.urlencoded({ extended: true })); // application/x-www-form-urlencoded
    app.use(multer()); // multipart/form-data
    ...
    

    Then add the dependencies in the package.json

    "body-parser": "^1.12.4",
    "multer": "^0.1.8"
    

    Now you can do things like the following in the /models/user.js (for any model)

      user.beforeRemote('create', function(ctx, unused, next) {
         console.log("The registered user is: " + ctx.req.body.email);
         next();
      });
    

    I hope this helps! :)

提交回复
热议问题