我正在设置一个 Express-Typescript 应用程序以使用 ApolloServer 创建 GraphQL 服务器。但是,我在尝试将expressMiddleware 用于 GraphQL 端点时遇到了类型错误。这是代码:
import "dotenv/config";
import express from 'express';
import cors from 'cors';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServer } from '@apollo/server';
const gqlServer = new ApolloServer({
typeDefs: `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello world!',
}
},
});
async function init() {
const app = express();
const port = Number(process.env.PORT) || 4000;
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
await gqlServer.start();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.use("/graphql", expressMiddleware(gqlServer)); // Error Here
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
}
init();
tsconfig.json 文件有
{
"compilerOptions": {
"target": "es2016",
"module": "CommonJS",
"rootDir": "./src",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
Package.json 文件有:
{
"name": "server",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsc-watch --onSuccess \"npm start\"",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@apollo/server": "^4.11.2",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"graphql": "^16.10.0"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/dotenv": "^8.2.3",
"@types/express": "^5.0.0",
"nodemon": "^3.1.9",
"tsc": "^2.0.4",
"tsc-watch": "^6.2.1",
"typescript": "^5.7.2"
}
}
错误: TypeScript 编译器抛出以下错误:
“RequestHandler
查看您的
package.json
,您使用的是 Express 版本 4,但您拥有 Express 5 的 @types/express
。这些不匹配。
"express": "^4.21.2",
"@types/express": "^5.0.0",
在您的
devDependencies
中,更改此行:
"@types/express": "^5.0.0",
到此
"@types/express": "^4.17.21",
然后重新安装您的软件包(
npm install
或yarn install
)。
Express v5 在
next
中,因此当您执行 npm install express
时,您会得到 v4,但是 DefinitelyTyped
(@types/*
的来源)已将 v5 发布为 latest
,因此当您执行 npm install @types/express
时,你得到v5。这意味着在新项目中,您必须具体说明,直到 Express5 完全发布或 DefinelyTyped 更新其 npm 标签。