Node.js execution error

Asked

Viewed 176 times

0

Hello, I have this error in my app:

Server Running On! URL: / Method: GET _http_outgoing.js:482 throw new ERR_HTTP_HEADERS_SENT('set'); ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client At Serverresponse.setHeader (_http_outgoing.js:482:11) At server.http.createServer (C: Users Samuel Melo da Silva Desktop Node.js index.js:13:8) At Server.Emit (Vents.js:193:13) at parserOnIncoming (_http_server.js:680:12) At Httpparser.parserOnHeadersComplete (_http_common.js:113:17)

code:

const http = require('http');

let server = http.createServer((req, res)=>{

    console.log('URL:', req.url);
    console.log('Method:', req.method);

    res.end('ok');

    switch(req.url){
        case '/':
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html');
            res.end('<h1>Olá</h1>');
            break;
        case '/users':
            res.statusCode = 200;
            res.setHeader("Content-Type", 'application/json');
            res.end(JSON.stringify({
                user:[{
                    name:'Samuel',
                    email: '[email protected]',
                    id: 1
                }]
            }));
            break;
    }
});

server.listen(300, '127.0.0.1', ()=>{

    console.log('Servidor Rodando!');

});

1 answer

3


The mistake is saying that you can’t change the headers of the reply after having already sent the same.

Note that you are using the command res.end('ok') and right after in your switch you do res.statusCode = 200 and res.setHeader(). That is not possible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.