前后端分离项目,后端自然要用到RESTful架构,之前一直使用express框架的,使用起来也是非常方便,不过仅仅是开发api,使用express有点大材小用了,很多功能用不到。新项目中,就尝试一下专门为api诞生的restify框架,以下简单记录一下使用过程。
主要先学习一下,所以分别要测试,post、put、delete、patch、get五种方法咯,所以新建以下几个路由,其中index是总路由。
add.js非常简单
export default async (req, res, next) => {
console.log(req.body)
res.send(201, { body: 'add' })
}
put.js也一样
export default async (req, res, next) => {
console.log(req.params.ID)
res.send(201, { hello: 'put' })
}
其他getone、delete、patch都差不多,我就不一一罗列了。
最后upload.js代码如下:
export default async (req, res, next) => {
console.log(`文件名:${req.files.word.name}`)
console.log(`文件尺寸:${(req.files.word.size/1024).toFixed(1)}KB`)
console.log(`文件路径:${req.files.word.path}`)
console.log(`文件类型:${req.files.word.type}`)
res.send(201, { hello: 'upload' })
}
然后是总路由index.js,分别导入以上子路由,不同的请求方法指向不同的路由,要注意一下,restify的del和experess的delete方法略有不同。
import list from './list.js'
import add from './add.js'
import put from './put.js'
import patch from './patch.js'
import del from './delete.js'
import getone from './getone.js'
import uploadRouter from './upload.js'
const Question = (server) => {
server.get('/question', list)
server.get('/question/:ID', getone)
server.post('/question', add)
server.post('/question/upload', uploadRouter)
server.put('/question/:ID', put)
server.patch('/question', patch)
server.del('/question', del)
}
export default Question
最后就是app.js文件,启动文件,再导入此路由即可,请注意pre方法和use方法的不同,已经注释。
import restify from 'restify'
import Question from './router/question/index.js'
import Guard from './router/guard.js'
import Guard2 from './router/guard2.js'
const server = restify.createServer({
name: 'API'
})
// pre()方法可以注册处理器到 pre 处理器链中。
// 那么对所有接收的 HTTP 请求,都会预先调用该处理器链中的处理器
// 最重要一点是,无论实际存在不存在此路由,pre都会处理请求
server.pre(Guard)
server.use(restify.plugins.bodyParser({
uploadDir: './upload',// 上传路径
multiples: false, // 是否可以上传到多个
mapFiles: true, // 不明
keepExtensions:true, // 是否保留扩展名
maxFieldsSize: 2 * 1024 * 1024 // 文件最大尺寸
}))
// 加了以下这句可以通过req.query获得json格式的query,如{q:abc}
// 不加的话,只能通过req.getQuery()获得,且返回的是q=abc这种格式,非json
server.use(restify.plugins.queryParser())
// use在确定路由之后执行的处理器链。
// 只有存在此路由,use才会处理请求。
server.use(Guard2)
Question(server)
server.listen(3001, '127.0.0.1', function () {
console.log('%s listen at %s', server.name, server.url)
})
最后我要说一下上传,必须使用这个restify.plugins.bodyParser插件,和express中使用multer组件完全不同,这个插件可以传入很多参数。具体可以点击官网。
最重要的就是uploadDir这个属性了,后面这是上传的路径,不过这里就有一个问题了,项目中所有路由如果有上传的话都要上传到这个目录了,难道不能根据不同的路由设置不同的目录?有点不合理。有大神知道的话,不吝赐教。