javascript - 当我在heroku中部署我的应用程序时获取html时出错
问题描述
这是我在 express node.js 中的 index.js 文件,该应用程序运行良好,直到我将它部署在 Heroku 上,在生产中它会抛出我的错误,就像服务器找不到我的 index.html 一样。
*-src ---index.html ---index.js *
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);
});
解决方案
您需要使用绝对文件路径: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
推荐阅读
- r - 从 tidyverse 管道中将交互()应用于用户指定的列
- python - 作业“WrappedAPIView 引发异常。TypeError:view() 缺少 1 个必需的位置参数:'request'
- fortran - 如何分隔中间有符号的字符串
- r - R中的马修斯相关系数函数(mcc)不起作用
- python - Pandas/Python,在目录中提取最新文件
- swift - 解释这段代码:使用字符串作为过滤函数
- bash - 如何用 BASH 中的整个文件替换匹配项?
- c - 使用c中的链表进行中缀到后缀转换
- javascript - 如何对从 API 获取的数据进行搜索过滤
- swift - HKWorkoutSession 没有完成?