簡體   English   中英

錯誤:發送標頭后無法設置標頭。 表達js

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

在這里,我試圖讀取一個簡單的文本文件,並將內容放在頁面上。 這是一個非常簡單的應用程序,但我仍然遇到問題。 下面是我的代碼,下面還附加了我的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"));

嘗試在您的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 ); 
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");
      }
    });
});

要設置內容類型,我們可以使用如下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

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM