【问题标题】:Error says http.createServer is not a function but it is错误说 http.createServer 不是一个函数,但它是
【发布时间】:2021-09-08 02:45:02
【问题描述】:

我在 node.js 应用上有这段代码:

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;

const server = http.createServer((req, res) => {
  res.sendFile(__dirname + '/index.html');
});

但我收到一条错误消息,说 createServer 不是函数,尽管您知道它是函数。如果我取出.Server(app),那么它可以工作,但是我不能使用我需要的快递。有办法吗?

谢谢。

【问题讨论】:

  • 您正在将 Express 内容与基本节点 http 模块相结合。你不需要 .createServer,只需要 app.listen。 expressjs.com/en/starter/hello-world.html
  • 原来是这样的。这样做的问题是,如果您访问 example.com/myapp 而末尾没有斜杠,那么它会说它找不到应用程序。您必须像这样访问:example.com/myapp/ 才能获取该页面。
  • 这个错误特别说Cannot GET /myapp
  • 我在这里看不到任何 /myapp。什么是在该路径下安装您的 API?
  • 一个名为 socket.io 的脚本。 myapp/ 是我安装它的文件夹。

标签: node.js express socket.io


【解决方案1】:

因为http.createServer() 只是实例化http.Server 的辅助方法。也可以使用http.Server()函数类进行实例化,所以有两种选择。

选项 1。

const express = require('express');
const http = require('http');

const app = express();
const port = process.env.PORT || 3000;
const server = http.createServer(app);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

server.listen(port);

选项 2。

const app = require('express')();
const server = require('http').Server(app);

const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

server.listen(port);

index.html:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  app
</body>

</html>

测试:

 ⚡  curl http://localhost:3000                                            
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  app
</body>

</html>%  

【讨论】:

  • 问题是,如果您访问 example.com/myapp 末尾没有斜杠,您会收到如下错误:Cannot GET /myapp 这会强制您像这样访问:example.com/myapp / 以获取索引页面。
猜你喜欢
  • 2016-03-07
  • 2020-12-21
  • 2012-08-11
  • 2018-11-21
  • 2021-11-06
  • 2016-04-05
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多