簡體   English   中英

標頭Node.js,發送后無法設置標頭

[英]Headers, Node.js , Can\'t set headers after they are sent

我是node.js的新手,正在實現靜態文件服務器。

我想做的就是從url中獲取文件名並顯示它。 運行代碼ID會收到此錯誤:

_http_outgoing.js:489拋出新錯誤(“發送頭后無法設置頭。”);

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

這是我的代碼

 #!/usr/bin/env node

/*
 *  Basic node.js HTTP server 
 */
const http = require('http');
const url = require('url');
const fs = require('fs');
const routes = Object.create(null);

function file(rew, res, serched) {
    let fileSerched = serched[serched.length - 1]
    fileSerched = __dirname + "/NodeStaticFiles/" + fileSerched;
    fs.readFile(fileSerched, function(err, data) {
        if (err) {
            res.statusCode = 500;
            res.end(`Error getting the file: ${err}.`);
        } else {
            res.setHeader('Content-type', 'text/plain');
            res.writeHead(200)
            res.end(data);
        }
    })
}

routes['file'] = file;

function onRequest(req, res) {
    const pathname = url.parse(req.url).pathname
    const uri = pathname.split('/', 3)[1]
    let splittedPathname = pathname.split('/')
    splittedPathname.shift()
    splittedPathname.shift()
    if (typeof routes[uri] === 'function') {
        routes[uri](req, res, splittedPathname);
    } else {
        res.statusCode = 404;
        res.end(`File not found!`);
    }
    res.end()
}
http.createServer(onRequest).listen(3000);
console.log('Server started at localhost:3000')

您需要確保您的代碼不會res.end()調用諸如res.end()類的東西。 例如:

function onRequest(req, res) {
    const pathname = url.parse(req.url).pathname
    const uri = pathname.split('/', 3)[1]
    let splittedPathname = pathname.split('/')
    splittedPathname.shift()
    splittedPathname.shift()
    if (typeof routes[uri] === 'function') {
        routes[uri](req, res, splittedPathname);
    } else {

    // THIS WILL CALL res.end() and continue on
       res.statusCode = 404;
       res.end(`File not found!`);
   }

   // THIS WILL CALL res.end() AGAIN!!
   res.end()
}

嘗試在if/else調用res.end()之后添加return

暫無
暫無

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

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