node.js - 如何将不断发布到端点的 Node.js 应用程序部署到 Heroku?
问题描述
我创建了一个非常简单的 Node 应用程序,它只有一个函数,每三秒就会访问一个 POST 端点。它控制台返回它与响应代码一起发布的次数。这是一个名为的文件中的完整代码fetch.js
:
const request = require('request');
let counter = 0
function vote(){
const options = {
method: 'POST',
url: 'https://voting-vote-producer.r7.com/vote',
headers: {
authority: 'voting-vote-producer.r7.com',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded',
accept: '*/*',
origin: 'https://afazenda.r7.com',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'https://afazenda.r7.com/a-fazenda-12/votacao',
'accept-language': 'en-US,en;q=0.9,pt;q=0.8'
},
form: {voting_id: '268', alternative_id: '648'},
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(response.statusCode);
console.log(`votos: `, counter)
counter++
})
}
setInterval(vote, 3000)
package.json
然后我根据 Heroku 的规范创建了一个脚本:
...
"scripts": {
"start": "node fetch.js"
},
...
如果我在本地运行npm start
或者node fetch.js
它可以工作。我可以在控制台日志中看到它。
但是,在成功部署到 Heroku 后,根据 Heroku 日志,我不断收到错误消息:
2020-11-19T15:15:02.738228+00:00 heroku[web.1]: State changed from crashed to starting
2020-11-19T15:15:05.839197+00:00 heroku[web.1]: Starting process with command `npm start`
2020-11-19T15:15:09.505292+00:00 app[web.1]:
2020-11-19T15:15:09.505330+00:00 app[web.1]: > fazenda@1.0.0 start /app
2020-11-19T15:15:09.505331+00:00 app[web.1]: > node fetch.js
2020-11-19T15:15:09.505331+00:00 app[web.1]:
2020-11-19T15:16:06.107217+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2020-11-19T15:16:06.130433+00:00 heroku[web.1]: Stopping process with SIGKILL
2020-11-19T15:16:06.251368+00:00 heroku[web.1]: Process exited with status 137
2020-11-19T15:16:06.326134+00:00 heroku[web.1]: State changed from starting to crashed
想法?
解决方案
默认情况下,Heroku 需要一个 HTTP 服务器才能工作。因此,您只需创建一个不执行任何操作的 HTTP 服务器。您可以为此使用内置的HTTP 模块。
例如,将以下内容添加到您的应用程序中:
const http = require('http');
const requestListener = function (req, res) {
res.writeHead(200);
res.end('Hello, World!');
}
const server = http.createServer(requestListener);
// this should be the last line
server.listen(parseInt(process.env.PORT) || 8080);
请注意,如果 Heroku 使用PORT
环境变量传递所需的端口。