Home > OS >  Nodejs: Cannot set headers after they are sent to the
Nodejs: Cannot set headers after they are sent to the

Time:05-30

I write this code with NodeJS:

const setOutput = (res, req, data) => {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(data));
}

app.post('/getDb', async (req, res, next) => {
    if (!req.body.hasOwnProperty('key')) {
        setOutput(res, req, {
            error: true,
            message: 'You must send key'
        })
    }
    
    const db = openDb(req.body.key);
    
    if (!db) {
        setOutput(res, req, {
            error: true,
            message: 'Not found key'
        })
    }

    setOutput(res, req, {
        error: false,
        message: 'DB create successful',
        data: {
            min: 0.1
        }
    });
})

This code work fine, but I get this error:

(node:253965) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

How can I stop anything after call setOutput?

Note: I don't want use switch or a lot of if else

CodePudding user response:

In your request, you're invoking setOutput multiple times which means the request will be sent to the client but the callback function in app.post keeps on executing because you haven't returned anything from app.post's callback you'd invoked the other function which in this case is setOuput so in nodejs world the error simply means that you'd send a response to the client now you can't prepare headers the simple solution would be to return after sending each request like this `

app.post('/getDb', async (req, res, next) => {
    if (!req.body.hasOwnProperty('key')) {
       return setOutput(res, req, {
            error: true,
            message: 'You must send key'
        })
    }
    
    const db = openDb(req.body.key);
    
    if (!db) {
        return setOutput(res, req, {
            error: true,
            message: 'Not found key'
        })
    }

    setOutput(res, req, {
        error: false,
        message: 'DB create successful',
        data: {
            min: 0.1
        }
    });
})

`

CodePudding user response:

Basically, you are trying to call setOutput arrow function multiple times in a request. That is why terminating the execution after sending may help:

if (!req.body.hasOwnProperty('key')) {
        setOutput(res, req, {
            error: true,
            message: 'You must send key'
        })
      return;
    }

const db = openDb(req.body.key);

if (!db) {
    setOutput(res, req, {
        error: true,
        message: 'Not found key'
    })
  return;
}
  • Related