简体   繁体   English

错误:发送标头后无法设置标头。 表达js

[英]Error: Can't set headers after they are sent. express js

Here I am trying to read a simple text file and put the content on my page. 在这里,我试图读取一个简单的文本文件,并将内容放在页面上。 It's a very simply app but I am still having issues. 这是一个非常简单的应用程序,但我仍然遇到问题。 Below is my code and I have also attached my github repo below. 下面是我的代码,下面还附加了我的github存储库。

https://github.com/shanemmay/ExpressJsProblem 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"));

Try replacing this block in your get function: 尝试在您的get函数中替换此块:

fs.readFile('test.txt', (err, data) =>
{
    res.set({
        'Content-Type': 'text/html'
    });
    res.status(200).send("<h1>test complete</h1>" + data);
});

That should duplicate the behavior you're looking for. 那应该复制您想要的行为。 The above will help you set headers if you need to, and explicitly set the status message, although, all you really need is this to do what you want: 上面的内容将帮助您设置标题,并显式设置状态消息,尽管,您真正需要的只是做您想要的事情:

res.send( "<h1>test complete</h1>" + data ); 
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");
      }
    });
});

To set the content type, we can use set method as below. 要设置内容类型,我们可以使用如下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);       
    });
});

Ref: http://expressjs.com/en/4x/api.html#res.set 参考: http : //expressjs.com/en/4x/api.html#res.set

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM