如何在Restify路由中设置中间件?

时间:2020-06-02 13:13:11

标签: node.js rest express middleware restify

我正在为我的Web应用程序使用restify节点js框架。 Sever.js文件包含以下代码:

var restify = require('restify')

var server = restify.createServer()

const schemas = require('./tools/schemaValidation');
const validation = require('./tools/validation');
// Add headers
server.use(function (req, res, next) {

    // Website you wish to allow to connect
   // res.setHeader('Access-Control-Allow-Origin', "http://localhost:8888");

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,accept');
    res.setHeader('Access-Control-Allow-Origin', "*");
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

//User create route
server.post('/user', validation(schemas.user.create), routes.users.create)

我在用户创建路由时添加了中间件作为 validation(schemas.user.create)

验证中间件在这里:

const Joi = require('joi'); 
console.log("i am here");
console.log("*****************************************************");
let middleware = (schema, property) => { 
  return (req, res, next) => { 
  const { error } = Joi.validate(req.body, schema); 
  const valid = error == null; 

  if (valid) { 
    next(); 
  } else { 
    const { details } = error; 
    const message = details.map(i => i.message).join(',');

    console.log("error", message); 
   res.status(422).json({ error: message }) } 
  } 
} 
module.exports = middleware;

架构文件在这里:

const Joi = require('joi') 
const schemas = { 
  user : { 
      create : Joi.object().keys({ 
            firstName: Joi.string().required(),
            lastName: Joi.string().required() 
        }) 
  }      
}; 
module.exports = schemas;

现在,问题是,每当我点击创建用户路由中间件时,它就不会运行。因此,任何人都可以帮助我解决这个问题,我要去哪里了?

0 个答案:

没有答案