首页 > 解决方案 > 当代码在本地运行时,为什么在 heroku 中使用 node.js 会给我不同的结果?

问题描述

我已将所有代码上传到 Heroku。但是,我被建议查看 Heroku 日志详细信息并在我的终端中接收此消息。

2019-02-12T13:23:48.102698+00:00 heroku[router]: at=error code=H10 
desc="App crashed" method=GET path="/favicon.ico" host=frozen- 
wildwood-17884.herokuapp.com request_id=55cdcdac-a94a-49f3-a050- 
920bad07f674 fwd="134.19.180.166" dyno= connect= service= status=503 
bytes= protocol=https

我还研究了其他页面并尝试将以下内容添加到我的 server.js 文件的底部,但没有运气。

app.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", 
this.address().port, app.settings.env);
});

对此问题的任何建议将不胜感激。

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express()

const apiKey = '****************';

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')

app.get('/', function (req, res) {
  res.render('index', {weather: null, error: null});
})

app.post('/', function (req, res) {
  let city = req.body.city;
  let url = `http://api.openweathermap.org/data/2.5/weather? 
q=${city}&units=metric&appid=${apiKey}`

request(url, function (err, response, body) {
  if(err){
  res.render('index', {weather: null, error: 'Error, please try 
again'});
} else {
  let weather = JSON.parse(body)
  if(weather.main == undefined){
    res.render('index', {weather: null, error: 'Error, please try again'});
  } else {
    let weatherText = `It's ${weather.main.temp} degrees in ${weather.name}!`;
    res.render('index', {weather: weatherText, error: null});
     }
   }
 });

})

结果显示在 heroku 应用程序的错误页面中。但是,该应用程序在本地运行良好。

标签: node.jsexpressheroku

解决方案


从您的最后一条评论和process.env.PORT未定义的情况来看,您似乎正试图在同一个 TCP 端口上运行两个侦听器。这不起作用,因为侦听器将打开端口进行读取,导致所有其他打开端口的尝试失败。


推荐阅读