![](/img/trans.png)
[英]How to send http responses to all the connected sockets with fastify-ws in node.js application?
[英]How to use a Fastify application with a plain Node.js HTTP server?
我想使用 Fastify 创建一个 REST API,但我想将它与我自己创建和配置的普通 Node.js http.Server
实例一起使用,而不是使用fastify.listen()
来创建套接字。
使用 express.js,您可以像这样将应用程序处理程序传递给http.createServer()
:
import http from "node:http";
import express from "express";
const expressApp = express();
// creating routes here
const httpServer = http.createServer(expressApp);
httpServer.listen({
port: 80,
host: "127.0.0.1",
});
我已经尝试过通过fastify()
创建的对象,但它不起作用。 还有其他方法吗?
您需要使用serverFactory
选项
const http = require('http')
let server
const serverFactory = (handler, opts) => {
server = http.createServer((req, res) => {
handler(req, res)
})
return server
}
const fastify = require('fastify')({ serverFactory })
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
fastify.ready(() => {
server.listen({ port: 8080 })
})
并且不使用 fastify.listen() 来创建套接字。
无论如何你都需要调用fastify.ready()
,否则插件将不会被加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.