user3225501
user3225501

Reputation: 74

Node.js piping streams with ajax and nodes http module

I have an express app with some ajax, calling some remote endpoints. At the moment, my api calls are posting to an endpoint on my local server. Express listens on these endpoints and pipes the request to the remote server and resolves the response.

This is working for most of my endpoints, except for one POST method which requires a query parameter of code and a body of type Array[int]. The response for each request to this endpoint returns 405. If I call the server endpoint directly within the ajax request, It returns successful. Does this issue ring a bell for anyone?

Here is what the data flow looks like.

$.ajax({
        type: "POST",
        url: "/promos/validate?code=testing",
        data: JSON.stringify([1]),
        success: function(data) {
           console.log(data)
        }.bind(this),
        error: function(xhr, status, err) {
           console.log(status)
        }.bind(this)
    });

And then we route with express

router.post('/promos/validate', function(req, res) {
  pipe(req, res).post(http://remoteUrl/promos/validate/code=testing);
});

In the post method, lives the http.request function which sends the following object as the options parameter

{ 
protocol: 'http:',
  query: '?code=testing',
  host: 'remote-api.com',
  port: 80,
  hostname: 'remote-api.com',
  href: 'http://remote-api.com?code=testing',
  path: '/promos/validate',
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'Content-Length': 8 } 
}

And finally we stream the request body to the server with write. Every time this happens, it returns 405. Any ideas?

Upvotes: 1

Views: 787

Answers (1)

user3225501
user3225501

Reputation: 74

Two things: the ajax request needed to set the content type to application/json and it turns out that the request was hitting 405 because the query was being separated into its own property when it should have been appended onto the 'path' property option.

I found this out by viewing the options list at Node.js docs - https://nodejs.org/api/http.html#http_http_request_options_callback

Upvotes: 0

Related Questions