【问题标题】:Node js server can only listen but does not establish connectionnode js服务器只能监听不能建立连接
【发布时间】:2022-01-17 11:10:39
【问题描述】:

一直在尝试创建一个简单的 node.js 服务器,借助 sendgrid 的 API 将电子邮件发送到指定的电子邮件地址。代码之前运行得很好。但是,在我尝试使用 Heroku 部署服务器后,终端指示服务器正在侦听但不响应浏览器请求。(浏览器只是永远加载页面,最终将无法连接。)我不记得了对代码进行任何更改。这是我关注的Heroku tutorial

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

app.use(express.static("accessories"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json);

app.get("/", (req, res) => {
    res.sendFile('index.html', { root: '.' });
})

app.post("/", function(req, res){
    let emailTo = req.body.email;
    let subjectLine = req.body.subject;
    let message = req.body.body;

    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);

    const msg = {
        to: emailTo,
        from: 'example@example.com',
        subject: subjectLine,
        text: message, 
        // html: message,
    }

    sgMail
    .send(msg)
    .then(() => {
        res.sendFile('success.html', {root: '.'});
        console.log('Email sent');
    })
    .catch((error) => {
        res.sendFile('failure.html' + error, {root: '.'});
        console.error(error);
  })

  const jsonData = JSON.stringify(msg);
  console.log(jsonData);
})

app.listen(3000, function(){
    console.log("Server is listenning on port 3000.");
});

【问题讨论】:

    标签: javascript html node.js heroku


    【解决方案1】:

    如果您在上面包含的内容正是正在部署的内容,则可能是因为 PORT 在app.listen 中被硬编码为 3000

    我有一段时间没有接触 Heroku,但我记得他们的 Dyno 公开了一个 PORT 环境变量 (process.env.PORT)——用它来设置你的端口,例如:

    const portNumber = process.env.PORT || 3000
    app.listen(portNumber, function(){
      console.log(`Server is listening on port ${portNumber}`);
    });
    

    尝试重新部署,看看这是否对您的问题有帮助 - 请参阅此处了解 Heroku 的“官方”初始存储库,该存储库应正确部署,您可以根据需要进行修改:https://github.com/heroku/node-js-getting-started

    【讨论】:

    • 感谢您指出这一点。我进行了更改,但不知何故它仍然向我显示相同的错误。但是,我最终能够通过以下方式解决该问题: 1. 根据您的建议更改端口号; 2.清除npm缓存; 3.杀死所有节点; 4.删除'node module'文件夹和package.json文件并重新安装。
    猜你喜欢
    • 1970-01-01
    • 2015-09-18
    • 2021-08-29
    • 2018-05-27
    • 2012-08-11
    • 1970-01-01
    • 2013-03-28
    • 2017-07-24
    • 2017-05-01
    相关资源
    最近更新 更多