我有我的第一个 node .js应用程序(在本地运行良好)-但我无法通过heroku部署它(第一次使用heroku).代码如下.所以我不想写那么多代码,所以我只想说,在我的网络中本地运行代码没有问题.

 var http = require('http');
 var fs = require('fs');
 var path = require('path');

 http.createServer(function (request, response) {

    console.log('request starting for ');
    console.log(request);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    console.log(filePath);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

 }).listen(5000);

 console.log('Server running at http://127.0.0.1:5000/');

知道吗?

推荐答案

Heroku会动态地为你的应用程序分配一个端口,所以你不能将端口设置为固定的数字.Heroku将端口添加到env中,这样您就可以从那里提取它.换个Angular 听这个:

.listen(process.env.PORT || 5000)

这样,当您在本地进行测试时,它仍然可以监听端口5000,但它也可以在Heroku上工作.

您可以在Node上查看Heroku文档.js here.

Node.js相关问答推荐

仅当所需文档是最后一个文档时才更新MongoDB,否则插入

如何使用MongoDB在Node.js 中向数组中添加项?

Sveltekit停靠的应用程序找不到从Build导入的包

如何在ejs模板中使用循环显示多个结果?

如何在Mongoose中调用动态Collection ?

Mongoose:如何使用填充进行查找

为什么 nginx 不将我的 react index.html 作为后备服务

为什么当我使用waitForSelector时 Puppeteer 导致我的测试套件挂起 30 秒,即使我在页面和浏览器上调用关闭?

Typescript typeRoots 未检测到类型定义

Express.js - 监听请求中止

来自 child_process.exec 的错误没有这样的设备或地址,管道有帮助.为什么?

带权限的机密 Rest-Api - 总是 403 - 我做错了什么?

为什么我在生产环境中 deproy Next.js 示例项目时 CSS 不起作用?

响应发送 200 而不是 403

如何申请在NextJS上下载文件的许可?

如何在 MongoDB collection.find() 上获取回调

通过 POST 请求将数据从 node.js 服务器发送到 node.js 服务器

如何解决'npm应该在 node repl之外运行,在你的普通shell中'

Nodejs续集批量更新

Node.js 中的 PHP exit()/die() 类似功能是什么