Fastify和Heroku的集成

5
我正在使用Heroku托管的简单Fastify服务器,但它似乎无法正常工作!在开发过程中一切看起来都很好!我收到的错误是:Error R10 (启动超时)-> Web进程在启动后60秒内未能绑定到$PORT。我收到的完整错误如下:

enter image description here

这是我使用的代码: server.js:
const fastify = require("fastify")();
const path = require("path");

fastify.register(require("fastify-static"), {
  root: path.join(__dirname, "/"),
});

fastify.get("/", function (req, reply) {
  reply.sendFile("index.html");
});

fastify.listen(process.env.PORT || 5000, (err) => {
  if (err) throw err;
  console.log(`server listening on ${fastify.server.address().port}`);
});

package.json:

{
"name": "test1",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "engines": {
    "node": "15.11.x"
  },
  "scripts": {
    "start": "node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fastify": "^3.14.0",
    "fastify-static": "^4.0.1"
  }
}

有时候,网站甚至无法加载!
非常感谢任何帮助!
谢谢!
2个回答

17

那是该库的一个问题。对于其他库(如express、django等),不需要指定地址。

请参见https://github.com/fastify/fastify/issues/709

更改:

.listen(process.env.PORT) 
.listen(process.env.PORT, '0.0.0.0')

1
我不得不将其更改为新的语法,因此.listen({port: process.env.PORT || 3000, host: '0.0.0.0'}) - Ayudh

2
当我同时使用nodemon作为本地服务器和Heroku作为生产环境时,以下内容适用于我:
await fastify.listen(process.env.PORT, process.env.HOST || '0.0.0.0');

并且在 package.json 文件中

"dev": "PORT=${PORT:=3000} HOST=${HOST:=localhost} nodemon"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接