我在我的 Nodejs 项目中使用 fastify 作为 Web 框架。我想从一个目录中调用所有路由,该目录在主 JS 文件中定义了基本路由,就像我们在express中所做的那样。我读过很多博客,但没有找到与我的问题相关的答案
就像在快递中一样,我们将路线分配为-
app.use('/user', user_route)
然后在 user_route 中我们定义所有其他路由方法。
在 fastify 中我用过
fastify.register(require('./routes/users'), { prefix: '/user' })
但这样就只能调用一个函数——
module.exports = function (fastify, opts, done) {
  fastify.get('/user', handler_v1)
  done()
}
如果我想调用多个路由函数怎么办?
我已经使用 Fastify 用 Node、PostgreSQL、Sequelize 编写了我的服务器应用程序。
现在我想使用 TypeScript。谁能告诉我如何开始使用 TypeScript 重写我的服务器应用程序。
我试图按照此处的 Fastify with Typescript 文档组合一个简单的端点:
https://www.fastify.io/docs/v3.1.x/TypeScript/
export default async function foo(fastify: any) {
       const MyInstance = new Foo(fastify.db);
       app.get<{ Querystring: IQueryString, Headers: IHeaders }>(
           "/foo",
           async (request: FastifyRequest, reply: FastifyReply) => {
              console.log(request.query); // *prints query object*
              const { queryObj } = request.query; // *Gives error: Object is of type 'unknown'*
              const result = await MyInstance.getFoo(queryObj);
              reply.status(200).send(result);
           }
       );
   }
当我尝试访问该对象时,为什么会出现错误?request.query如何修复该错误?
我刚刚开始使用 Typescript 来使用 Fastify,并且非常喜欢它。
但是,我试图弄清楚是否可以输入响应负载。我有用于序列化工作的响应模式,这可能就足够了,但我有内部类型化的对象(例如 IUser),最好让 Typescript 检查。
以下内容效果很好,但我想返回一个 TUser 例如,如果我返回不同的内容,则有打字稿。使用模式仅仅排除字段。
interface IUser {
    firstname: string,
    lastname: string
} // Not in use in example
interface IUserRequest extends RequestGenericInterface {
  Params: { username: string };
}
const getUserHandler = async (
  req: FastifyRequest<IUserRequest, RawServerBase, IncomingMessage | Http2ServerRequest>
) => {
  const { username } = req.params;
  return { ... }; // Would like to return instance of IUser
};
app.get<IUserRequest>('/:username', { schema }, getUserHandler);
我可以为响应扩展一个等效的 RequestGenericInterface 吗?
小更新:似乎可以使用 …
我从 fastify cli 生成了 fastify 项目,然后我真的想使用记录器系统并将其写入文件
下面的代码是我尝试的方法,但是当我发送请求时,它还没有写入任何日志文件,并且系统也不会创建任何文件。
import { join } from 'path';
import AutoLoad, {AutoloadPluginOptions} from 'fastify-autoload';
import { FastifyLoggerOptions, FastifyPluginAsync } from 'fastify';
export type AppOptions = {
  // Place your custom options for app below here.
} & Partial<AutoloadPluginOptions> & Partial<FastifyLoggerOptions>;
const app: FastifyPluginAsync<AppOptions> = async (
    fastify,
    opts
): Promise<void> => {
  // Place here your custom code!
  opts.level = 'info'
  opts.file = 'logger'
  fastify.log.info('Test log')
  // Do not touch the following lines
  // This loads …我需要从处理程序文件访问 fastify 实例。我根本不记得我应该怎么做。
指数:
fastify.register(require('./routes/auth'), {
  prefix: '/auth'
})
路线/授权:
module.exports = function(fastify, opts, next) {
  const authHandler = require('../handlers/auth')
  fastify.get('/', authHandler.getRoot)
  next()
}
处理程序/授权:
module.exports = {
  getRoot: (request, reply) {
    // ACCESS FASTIFY NAMESPACE HERE
    reply.code(204).send({
      type: 'warning',
      message: 'No content'
    })
  }
}
谢谢!
我的代码中有这个路由器
fastify.get('/:link', (req, reply) => {
    req.params.url = req.host+req.url;
    reply.view("template.ejs",req.params);
});
我正在尝试捕获 URL 并在模板中处理它们。URL 均已encodeURIComponent转义。由于某种原因,某些 URL 会返回 404 not found,我不确定为什么。这是有效的链接。
这是行不通的。
错误是
{
"message": "Route GET:/https%3A%2F%2Fs7386.pcdn.co%2Fwp-content%2Fuploads%2F2016%2F07%2Fadd-on-direct-link-tracking-771x386.png not found",
"error": "Not Found",
"statusCode": 404
}
我使用的是带有节点 v12.8.0 和 fastify 2.8.0 的 Windows 10
我有使用 Fastify 的新 NestJS 应用程序。当尝试时,npm run test:e2e我收到以下错误:
[Nest] 14894   - 11/19/2021, 10:29:10 PM   [ExceptionHandler] The "@nestjs/platform-express" package is missing. Please, make sure to install this library ($ npm install @nestjs/platform-express) to take advantage of NestFactory.\n  \xe2\x97\x8f  process.exit called with "1"\n\n      12 |     }).compile();\n      13 | \n    > 14 |     app = moduleFixture.createNestApplication();\n         |                         ^\n      15 |     await app.init();\n      16 |   });\n      17 | \n\n      at Object.loadPackage (../node_modules/@nestjs/common/utils/load-package.util.js:13:17)\n      at TestingModule.createHttpAdapter (../node_modules/@nestjs/testing/testing-module.js:25:56)\n      at TestingModule.createNestApplication (../node_modules/@nestjs/testing/testing-module.js:13:43)\n      at Object.<anonymous> (app.e2e-spec.ts:14:25)\n\n RUNS …我的公司有一个定制开发的记录器包,我们想在 fastify 中使用它作为默认记录器。我试图通过下面这个简单的例子来了解如何注册我的记录器,但是 fastify 总是使用 Pino。
索引.js
const log = require("./Logger");
const fastify = require("fastify")({ logger: log });
fastify.get("/", (request, reply) => {
    request.log(
        "includes request information, but is the same logger instance as `log`"
    );
    reply.send({ hello: "world" });
});
fastify.listen(3000)
记录器.js
function Logger(...args) {
    this.args = args;
}
Logger.prototype.info = function(msg) {
    console.log("myLogger", msg);
};
logger.js也包含error, debug, fatal, warn, trace,child函数但函数体是相同的。
结果是:
{"level":30,"time":1553095994942,"msg":"Server listening at http://127.0.0.1:3000","pid":14543,"hostname":"VirtualBox","v":1}
whiitch 是默认的 Pino 输出。
服务器.ts
import fastify from "fastify";
import cookie from 'fastify-cookie';
import apiRoute from './routes/api';
import jwtPlugin from "./plugins/jwtPlugin";
import closePlugin from "./plugins/closePlugin";
import path from "path";
const PORT = parseInt(process.env.PORT!, 10)
export default class Server {
    app = fastify({ logger: true })
    constructor() {
        this.setup()
    }
    setup() {
        this.app.get('/', (request, reply) => {
            reply.send({ hello: 'world' })
        })
        this.app.register(apiRoute, { prefix: '/api' })
        this.app.register(cookie)
        this.app.register(require('fastify-url-data'))
        this.app.register(jwtPlugin)
        this.app.register(closePlugin)
        this.app.setErrorHandler((error, request, reply) => {
            reply.send({
                statusCode: error.statusCode,
                name: error.name,
                message: error.message,
                validation: error.validation, …fastify ×10
node.js ×7
typescript ×4
javascript ×2
express ×1
handler ×1
logging ×1
nestjs ×1
postgresql ×1
routes ×1
sequelize.js ×1