Sunday 19 March 2017

Can't set headers after they are sent Node / Express

I am trying to post data from a form on the client side using jquery to a post route that sends data to an api in node / express.

I am getting the error Can't set headers after they are sent and I can't figure out why.

How can I fix this?

Client:

<input id="prospect-form" type="text" placeholder="Email Address" class="form-control" style="vertical-align: baseline; display:inline-block; background-color: white; border: none;" onClick="submitData()" />

<script charset="utf-8">
    var submitData = function() {
      var data = $("prospect-form").serialize();
      $.post("/prospect/" + data, function() {
        console.log("data sent");
      })
      .done(function() {
        console.log("data success");
      })
      .fail(function() {
        console.log("data failed");
      })
      .always(function() {
        console.log("data finished");
      })
    }
</script>

Express:

router.post('/prospect/:query', function(req, res) {
  var data = req.params.query;
  var options = {
    url: "https://prospect.io/api/public/v1/prospects",
    formData: data,
    headers: {
      "Authorization": "",
      "Content-Type": "application/vnd.api+json; charset=utf-8",
    }
  }

  function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info);
    }
  }

  request.post(options, callback) //post

  res.end()

}) //router post

Thanks so much!



via Quesofat

No comments:

Post a Comment