Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 错误:Can';t在发送邮件后设置邮件头。快递js_Javascript_Node.js_Express_Header - Fatal编程技术网

Javascript 错误:Can';t在发送邮件后设置邮件头。快递js

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

在这里,我试图阅读一个简单的文本文件,并把内容放在我的页面上。这是一个非常简单的应用程序,但我仍然有问题。下面是我的代码,我还附上了我的github回购协议

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);       
    });
});