如何将连接升级到 HTTP 或 H2? 我正在运行阿波罗服务器,并且希望能够升级到安全连接。我已经生成了自签名证书。这是我的 server.js 文件的代码。
const {ApolloServer} = require("apollo-server");
const { resolvers } = require("./graphql/resolvers");
const FileSystem = require("node:fs/promises");
//Define function
async function startServer(){
//Read file as text
const typeDefs = await FileSystem.readFile("./graphql/type-defs.graphql",{
encoding: 'utf-8',
});
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen(8080).then(({url})=>{
console.log(`The API is running at ${url}`);
});
}
//Call the start server function
startServer();
要将 Apollo 服务器升级为使用 HTTPS 或 HTTP/2,您需要对代码进行一些调整以包含 SSL/TLS 选项并指定必要的证书和密钥文件。
以下是修改 server.js 文件以启用具有自签名证书的 HTTPS 的方法:
const { ApolloServer } = require("apollo-server");
const { resolvers } = require("./graphql/resolvers");
const FileSystem = require("node:fs/promises");
const https = require("https");
// Define function
async function startServer() {
// Read file as text
const typeDefs = await FileSystem.readFile("./graphql/type-defs.graphql", {
encoding: "utf-8",
});
const server = new ApolloServer({
typeDefs,
resolvers,
});
// Load SSL/TLS certificate and key
const options = {
key: await FileSystem.readFile("path_to_your_private_key.key"),
cert: await FileSystem.readFile("path_to_your_certificate.crt"),
};
// Create HTTPS server
const httpsServer = https.createServer(options, server);
httpsServer.listen(443, () => {
console.log("The API is running over HTTPS at port 443");
});
}
// Call the start server function
startServer();
将“path_to_your_private_key.key”和“path_to_your_certificate.crt”替换为您的自签名证书和私钥文件的路径。
如果你想使用HTTP/2,你可以以类似的方式利用http2模块。只需将 https 替换为 http2 并使用 createSecureServer 而不是 createServer 即可。