在heroku中部署我的应用程序时获取html错误

时间:2020-05-12 12:40:18

标签: javascript node.js express heroku

这是我在express node.js中的index.js文件,该应用程序可以正常运行,直到将其部署到Heroku上为止,然后在生产环境中运行。它抛出了该错误,例如服务器找不到我的index.html。 >

*-src --- index.html --- index.js enter image description here *

app.use(express.urlencoded({ extended: true }))

function renderHTML(path, response) {
    fs.readFile(path, null, function(error, data) {
        if (error) {
            response.writeHead(404);
            response.write('File not found!');
        } else {
            response.write(data);
        }
        response.end();
    });
}

app.get('/', function (req, res) {
  renderHTML('./index.html', res);
});

1 个答案:

答案 0 :(得分:2)

您需要使用绝对文件路径:path.resolve(__dirname, './index.html')。例如

文件结构:

.
├── package-lock.json
├── package.json
└── src
    ├── index.html
    └── index.js

index.js

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();

app.use(express.urlencoded({ extended: true }));

function renderHTML(path, response) {
  fs.readFile(path, null, function(error, data) {
    if (error) {
      response.writeHead(404);
      response.write('File not found!');
    } else {
      response.write(data);
    }
    response.end();
  });
}

app.get('/', function(req, res) {
  // renderHTML('./index.html', res);
  renderHTML(path.resolve(__dirname, './index.html'), res);
});

app.listen(process.env.PORT || 3000, () => console.log('Server is listening on port 3000'));

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    This is html
  </body>
</html>

package.json

{
  "name": "61751970",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.js",
  "engines": {
    "node": "10.x"
  },
  "scripts": {
    "start": "node ./src/index.js"
  },
  "keywords": [],
  "author": "mrdulin",
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.1"
  }
}

通过heroku logs --tail检查访问日志:

2020-05-19T06:53:49.000000+00:00 app[api]: Build succeeded
2020-05-19T06:53:53.715284+00:00 app[web.1]: 
2020-05-19T06:53:53.715304+00:00 app[web.1]: > 61751970@1.0.0 start /app
2020-05-19T06:53:53.715304+00:00 app[web.1]: > node ./src/index.js
2020-05-19T06:53:53.715304+00:00 app[web.1]: 
2020-05-19T06:53:53.975992+00:00 app[web.1]: Server is listening on port 26862
2020-05-19T06:53:54.300011+00:00 heroku[web.1]: State changed from starting to up
2020-05-19T06:54:00.891168+00:00 heroku[router]: at=info method=GET path="/" host=secret-mesa-39686.herokuapp.com request_id=9df765f8-e1a3-4015-a376-c6d9e0c6f645 fwd="118.183.246.243" dyno=web.1 connect=0ms service=20ms status=200 bytes=367 protocol=https

enter image description here

相关问题