简体   繁体   English

标头Node.js,发送后无法设置标头

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

I'm new in node.js and I'm implementing a Static file server. 我是node.js的新手,正在实现静态文件服务器。

what i'm trying to do is just get the file name from the url and display it. 我想做的就是从url中获取文件名并显示它。 running the code id get this error: 运行代码ID会收到此错误:

_http_outgoing.js:489 throw new Error('Can\\'t set headers after they are sent.'); _http_outgoing.js:489抛出新错误(“发送头后无法设置头。”);

Error: Can't set headers after they are sent. 错误:发送标头后无法设置标头。

this is my code 这是我的代码

 #!/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')

You need to make sure your code won't call something like res.end() more than once. 您需要确保您的代码不会res.end()调用诸如res.end()类的东西。 For example: 例如:

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

try adding a return after you call res.end() in an if/else 尝试在if/else调用res.end()之后添加return

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

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