简体   繁体   中英

Can't set headers after they are sent after first request only

i'm having a specific problem with the error "Can't set headers after they are sent".

The code is this one:

create: (request, response, next) ->
socket = @app.socket

#
# This method will be used to call the right method inside
# the emails service.
data = JSON.stringify(
  Object.assign request.body.data, method: 'server'
)

socket.send data

socket.on 'message', (result) =>
  result = JSON.parse(
    result.toString()
  )

  if result.code is 'success'
    @model.insertAsync request.body
      .then (result) ->
        response.json data: result
        return
      .catch next
    return
return

I'm using two servers and socket connection to communication between them. When i want create a email, i send a message for this other server and wait for the result, if the result is "success", i send the data back (i'm using Ember, so i need send the data after saving it). Now the problem: when i send the email for the first time everything works normal, when i try for the second time, a error message shows in my terminal:

Error: Can't set headers after they are sent.

According to express, the error is in this line:

response.json data: result

or in JS:

response.json({data: result});

The code in pure JS:

create: function(request, response, next) {
    var data, socket;
    socket = this.app.socket;
    data = JSON.stringify(Object.assign(request.body.data, {
      method: 'server'
    }));
    socket.send(data);
    socket.on('message', (function(_this) {
      return function(result) {
        result = JSON.parse(result.toString());
        if (result.code === 'success') {
          _this.model.insertAsync(request.body).then(function(result) {
            response.json({
              data: result
            });
          })["catch"](next);
        }
      };
    })(this));
  }

Thanks in advance, guys!

Most likely what is happening is you are receiving more than one successful "message" and so it's calling response.json() multiple times.

You could fix this by changing on('message') to once('message') so that the event handler only executes once. However, if that one message is not successful, a response won't be sent. So you may need to either add an else to your if (result.code === 'success') or leave on('message') and introduce some sort of guard variable so that the code inside the if is only executed once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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