1

I'm using Supertest (and thus Superagent) for some API testing on a Node.js project. I have a particular route that returns different content based on the type of request. Using expressJS's req.xhr, the code will return JSON if true or issue a redirect if false. I want to account for this in my tests but I'm struggling to get Superagent to mimic an XHR GET request.

According to ExpressJS documentation, it's looking for the X-Requested-With header in the request to be set to the value XMLHttpRequest. When I try to set this header using .set('X-Requested-With', 'XMLHttpRequest') I get

Unhandled rejection Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)

Odd thing is, I can set other headers, even before this one, just fine .set('Accept', 'application/json'). If the headers have already been written, this should fail too, but it doesn't. Also, checking res.request.req._headers, it appears nothing else is setting X-Requested-With so it's not like something else gave it a value either.

Matt Molnar
  • 2,412
  • 3
  • 22
  • 28
  • I'm not positive this will fix it, but is your `.set('Accept', 'application/json')` the last item, or are you trying to set the X-Requested-With header after you set the Accept header? – Machtyn Aug 10 '16 at 19:18
  • @Machtyn Thanks but I checked and it doesn't make a difference. I even commented out the `Accept` header altogether and the error is the same. – Matt Molnar Aug 15 '16 at 12:59

0 Answers0