Search code examples
node.jsexpressfeathersjs

FeathersJs: Cannot set headers


I am trying to set the content-type header on a route in a feathersjs app.

I keep running into this error - error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

This is how I am trying to set the headers --

const myService = {
  create(data, params) {   // create == POST request
    console.log(data);
    return Promise.resolve(); 
  }
};

function setContent(req, res, next) {
  res.setHeader('content-type', 'text/plain');
  res.end();
  next();
}

app.use('/incoming', myService, setContent);

I am guessing return Promise.resolve(); also sets the header. How do i go about overriding that?


Solution

  • The error is not coming from your middleware but the Feathers one registered after because you are ending the response with res.end() and then still calling next() which is probably not what you want. It should be either

    function setContent(req, res, next) {
      res.setHeader('content-type', 'text/plain');
      res.end();
    }
    

    Or

    function setContent(req, res, next) {
      res.setHeader('content-type', 'text/plain');
      next();
    }
    

    Also, service methods always have to return an object, so it should be at least return Promise.resolve(data); or return Promise.resolve({});