Express 应用程序作为 http.createServer 的参数

Posted

技术标签:

【中文标题】Express 应用程序作为 http.createServer 的参数【英文标题】:Express app as argument of http.createServer 【发布时间】:2017-02-01 01:41:27 【问题描述】:

当我想使用 express.Application 作为 http.createServer 的参数时,我遇到了这个错误:

error TS2345: Argument of type 'Application' is not assignable to parameter of type '(request: IncomingMessage, response: ServerResponse) => void'.

我的代码:

import * as express from "express"
let app: express.Application = express();
...
import * as http from "http"
let httpServer = http.createServer(app);
httpServer.listen(process.env.HTTP_PORT, (): void => 
    console.log(`HTTP Listen on $process.env.HTTP_PORT`)
);

typings.json:


  "dependencies": 
    "body-parser": "registry:npm/body-parser#1.15.2+20160815132839",
    "express": "registry:npm/express#4.14.0+20160911114220"
  ,
  "globalDependencies": 
    "dotenv": "registry:dt/dotenv#2.0.0+20160327131627",
    "errorhandler": "registry:dt/errorhandler#0.0.0+20160316155526",
    "express-serve-static-core": "registry:dt/express-serve-static-core#4.0.0+20160914120416",
    "method-override": "registry:dt/method-override#0.0.0+20160317120654",
    "morgan": "registry:dt/morgan#1.7.0+20160524142355",
    "node": "registry:dt/node#6.0.0+20160921192128"
  

【问题讨论】:

【参考方案1】:

我解决了。 只需要更新类型。我当前的 typings.json 文件:


  "globalDependencies": 
    "dotenv": "registry:dt/dotenv#2.0.0+20160327131627",
    "errorhandler": "registry:dt/errorhandler#0.0.0+20160316155526",
    "express": "registry:dt/express#4.0.0+20160708185218",
    "express-serve-static-core": "registry:dt/express-serve-static-core#4.0.0+20160916114806",
    "method-override": "registry:dt/method-override#0.0.0+20160317120654",
    "morgan": "registry:dt/morgan#1.7.0+20160524142355",
    "node": "registry:dt/node#6.0.0+20160921192128",
    "serve-favicon": "registry:dt/serve-favicon#0.0.0+20160316155526"
  ,
  "dependencies": 
    "body-parser": "registry:npm/body-parser#1.15.2+20160815132839",
    "serve-static": "registry:npm/serve-static#1.11.1+20160810053450"
  

【讨论】:

看起来你打字的不同之处在于你降级了 Express 版本。那正确吗?如果您提供有关更改内容和原因的更多信息,将会很有帮助。

以上是关于Express 应用程序作为 http.createServer 的参数的主要内容,如果未能解决你的问题,请参考以下文章

启动 node.js express 服务器作为服务

列出服务器上的静态内容并使用 Express 将其作为 JSON 返回

在 KrakenJS/Express 中加载 socket.io 作为模块

关于使用express作为spa应用服务的问题

在Express中作为POST请求的结果呈现视图

对本地主机的调用不适用于 ReactJS/Axios/Express