在这里,我试图读取一个简单的文本文件并将其内容放在页面上。这是一个非常简单的应用程序,但我仍然遇到问题。下面是我的代码,下面还附加了我的github存储库。
https://github.com/shanemmay/ExpressJsProblem
const express = require('express');
const fs = require('fs');
const app = express();
app.get('/', (req,res) =>
{
//trying to write some basic content to the page
fs.readFile('test.txt', (err, data) =>
{
res.writeHead(200, {'Content-Type': 'text/html'});
res.send("<h1>test complete</h1>");
res.write(data);
});
});
app.post("/post", (req,res) =>
{
//res.send("post");
});
app.listen(8080, () => console.log("App launched"));
答案 0 :(得分:0)
尝试在您的get函数中替换此块:
fs.readFile('test.txt', (err, data) =>
{
res.set({
'Content-Type': 'text/html'
});
res.status(200).send("<h1>test complete</h1>" + data);
});
这应该重复您要寻找的行为。上面的内容将帮助您设置标题,并明确设置状态消息,尽管您真正真正所需要做的只是这样做:
res.send( "<h1>test complete</h1>" + data );
答案 1 :(得分:0)
const fs = require('fs');
const filePath = "/path/to/file"
app.get('/', (req,res) => {
fs.exists(filePath, function(exists){
if (exists) {
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + fileName
});
fs.createReadStream(filePath).pipe(res);
} else {
res.writeHead(400, {"Content-Type": "text/plain"});
res.end("ERROR File does not exist");
}
});
});
答案 2 :(得分:0)
要设置内容类型,我们可以使用set
方法,如下所示。
app.get('/', (req,res) =>
{
//trying to write some basic content to the page
fs.readFile('test.txt', (err, data) =>
{
res.set('Content-Type', 'text/html');
res.send(data);
});
});
参考: http://expressjs.com/en/4x/api.html#res.set
希望有帮助