Javascript 错误:Can';t在发送邮件后设置邮件头。快递js
在这里,我试图阅读一个简单的文本文件,并把内容放在我的页面上。这是一个非常简单的应用程序,但我仍然有问题。下面是我的代码,我还附上了我的github回购协议Javascript 错误:Can';t在发送邮件后设置邮件头。快递js,javascript,node.js,express,header,Javascript,Node.js,Express,Header,在这里,我试图阅读一个简单的文本文件,并把内容放在我的页面上。这是一个非常简单的应用程序,但我仍然有问题。下面是我的代码,我还附上了我的github回购协议 const express=require('express'); 常数fs=要求('fs'); 常量app=express(); 应用程序获取(“/”,(请求,请求)=> { //尝试在页面中写入一些基本内容 fs.readFile('test.txt',(err,data)=> { res.writeHead(200,{'Conten
const express=require('express');
常数fs=要求('fs');
常量app=express();
应用程序获取(“/”,(请求,请求)=>
{
//尝试在页面中写入一些基本内容
fs.readFile('test.txt',(err,data)=>
{
res.writeHead(200,{'Content-Type':'text/html'});
res.send(“测试完成”);
res.write(数据);
});
});
app.post(“/post)”,(请求、回复)=>
{
//res.send(“post”);
});
app.listen(8080,()=>console.log(“应用启动”);
尝试在get函数中替换此块:
fs.readFile('test.txt', (err, data) =>
{
res.set({
'Content-Type': 'text/html'
});
res.status(200).send("<h1>test complete</h1>" + data);
});
fs.readFile('test.txt',(err,data)=>
{
res.set({
“内容类型”:“文本/html”
});
资源状态(200)。发送(“测试完成”+数据);
});
这应该会重复你想要的行为。如果需要,上述内容将帮助您设置标题,并显式设置状态消息,不过,您真正需要做的就是这样做:
res.send( "<h1>test complete</h1>" + data );
res.send(“测试完成”+数据);
要设置内容类型,我们可以使用下面的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);
});
});
参考:
希望有帮助对于给定的请求,当您多次发回响应时,会发生此错误。这里您将发送两次,首先使用
res.send
,然后使用res.write
。
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");
}
});
});
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);
});
});