代码拉取完成,页面将自动刷新
配置相关的工具项目内容: 飞书工具接入:分支代码:https://gitee.com/node-project-summary/feishu-nestjs-swagger.git
Nest framework TypeScript starter repository.
$ pnpm install
# development
$ pnpm run start
# watch mode
$ pnpm run start:dev
# production mode
$ pnpm run start:prod
# unit tests
$ pnpm run test
# e2e tests
$ pnpm run test:e2e
# test coverage
$ pnpm run test:cov
fastify是基于Node.js的高性能Web服务器,它专注于性能和可扩展性。 它使用了最新的技术,如HTTP/2和TLS。fastify的性能比express要高得多,因为fastify是基于事件驱动的,而express是基于回调的。
从API上来看,fastify和express是基本差不多的. 先安装
//index.js
const fastify = require('fastify')({ logger: true })
//声明一个最简单的路由
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
//启动服务
setImmediate(async () => {
try {
await fastify.listen(process.env.PORT||3000,'0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
})
这样就在本地端口3000上启动了一个简单的服务。打眼望去,整个框架完全支持async/await,写法上基本与express相同,但是减少了很多配置,例如不用配置body的解析,fastify将根据返回值自动处理
插件的使用也和express也差不多,而且基本上express常用的插件也有对应的fastify版本
fastify.route({
method:'GET',
url:'/123'
async handler(req,reply){
return "who's your daddy"
}
})
如果是express,增加一个跨域模块:express-cross,或koa2-cors
var cors = require('express-cross');
app.use(cors(true, ["localhost", "google.com"], ["foo": "bar"]));
但是fastify有一个简单模块:fastify-helmet模块是Fastify 的重要安全标头。它是头盔周围的一个小小的包装纸。
const fastify = require('fastify')({
logger: true
})
const to = require('await-to-js').default
const request = require("request-promise");
const baseUrl = 'http://192.168.0.199:8080'
fastify.register(
require('fastify-helmet'),
// Example disables the `contentSecurityPolicy` middleware but keeps the rest.
{ contentSecurityPolicy: false }
)
fastify.register(
require('fastify-cors'),
{
optionsSuccessStatus:204
}
)
fastify.get('/', async (request, reply) => {
return 'hello world'
})
fastify.route({
method: ['GET','POST','PUT','DELETE'],
url: '*',
handler: async (req, reply) => {
const options = {
method: req.method,
uri: baseUrl + req.url,
json: true
}
if(req.query){
options.qs = req.query
}
if(['POST','PUT'].includes(req.method)){
options.body = req.body
}
return await request(options)
}
})
setImmediate(async () => {
try {
await fastify.listen(process.env.PORT||3000,'0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
})
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。