标题,Node.js,发送后不能设置标题

时间:2017-10-29 22:34:42

标签: javascript node.js server

我是node.js的新手,我正在实现静态文件服务器。

我正在尝试做的只是从网址获取文件名并显示它。运行代码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')

1 个答案:

答案 0 :(得分:0)

您需要确保您的代码不会多次调用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()
}

return

中致电res.end()后尝试添加if/else