Luiz Alves
Luiz Alves

Reputation: 2645

Node server can´t set headers after sent

I have a node server and an angularJS app.

I have a route to get informations about one record.

The route is '/pacientes/:id'

When I request data from that route i am getting an error.

What am I doing wrong?

//error:

Error: Can't set headers after they are sent.
    at ServerResponse.setHeader (_http_outgoing.js:367:11)
    at ServerResponse.header (C:\nodeapp\cloudapp\node_modules\express\lib\respo
nse.js:719:10)
    at ServerResponse.send (C:\nodeapp\cloudapp\node_modules\express\lib\respons
e.js:164:12)
    at ServerResponse.json (C:\nodeapp\cloudapp\node_modules\express\lib\respons
e.js:250:15)
    at C:\nodeapp\cloudapp\server.js:973:10
    at Array.forEach (native)
    at C:\nodeapp\cloudapp\server.js:971:13
    at Layer.handle [as handle_request] (C:\nodeapp\cloudapp\node_modules\expres
s\lib\router\layer.js:95:5)
    at next (C:\nodeapp\cloudapp\node_modules\express\lib\router\route.js:131:13
)
    at Route.dispatch (C:\nodeapp\cloudapp\node_modules\express\lib\router\route
.js:112:3)

Here is app controller:

angular.module("clinang").controller('ProcedimentosCtrl',['$scope','$http','$state',function($scope,$http,$state){
      $scope.modelo={}
      var tipoId=$state.params.tipoId;
      if (tipoId) {
         $http.get('/pacientes/' + tipoId).then(function(response){
            $scope.modelo=response.data;
        }, function(error){
          console.log(error)
        });
      }
}]);

node - server.js

    var express = require('express');
    var bodyParser = require('body-parser');
    var jwt = require('jsonwebtoken');
    var expressJwt = require('express-jwt');
    var path = require('path');
    var app = express();

    // Define the port to run on
    app.set('port', process.env.port || 80);

    app.use(bodyParser.json());

    app.all('*', function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type');
      next();
    });

    var pacientes=[
        {id:1, nome:'Joao'},
        {id:2, nome:'Maria'}
    ];


    app.get('/pacientes/:id', function(req, res) {
      pacientes.forEach(function (paciente) {
        if (paciente.id == req.params.id) {
             res.json(paciente);
             return;
        }
      });
      res.status(404).end();
    });

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.status(404).end();
});

// Listen for requests
var server = app.listen(app.get('port'), function() {
  var port = server.address().port;
  console.log('Magic happens on port ' + port);
});

Upvotes: 0

Views: 223

Answers (1)

Omri Luzon
Omri Luzon

Reputation: 4214

You are trying to send multiple responses to the same request from the client, but you can only send it once.

Change this:

pacientes.forEach(function (paciente) {
  if (paciente.id == req.params.id) {
       res.json(paciente);
       return;
  }
});

To this:

var result;
pacientes.forEach(function (paciente) {
  if (paciente.id == req.params.id) {
       result = paciente;
  }
});
if (result !== undefined) {
  res.json(result);
} else {
  res.sendStatus(404);
}

The functions res.json, and res.sendStatus sets the header and the response's body, and call the .end() function after that, so you don't need to do it.

Upvotes: 2

Related Questions