Problems sending a Node.js http post request to an ASP.NET ajax service

Problems sending a Node.js http post request to an ASP.NET ajax service

Problem

I’m writing a some node code, which to simulate a ASP.NET ajax client call. It is made as a http post request to the server, and I’ve managed to setup the request headers and body perfectly with the OS X tool CocoaRestClient. With this tool the server responds perfectly as expected. When I try to do the same thing with Node.js, with the ‘request’ module, it fails:

My script:

var request = require('request');

request.post({
    'uri': 'http://[The Url]/[The Service].asmx/[The Operation]',
    'json': '{"callbackcontextkey":"[the context key]",[The set of json formatted key/value pairs] }',
    'headers': { }
}, function(e, r, body) {
    console.log("Response error: %j", e);
    console.log("Response r: %j", r);
    console.log("Response body: %j", body);
});

When I’m using the CocoaRestClient tool, all I specify is the Content-Type (application/json) parameter, and then just the request body as specified in the code (the ‘json’ attribute value). My code makes the server side return this:

“There was an error processing the request.”

And I can also see this in the response:

“jsonerror”:”true”

What am I doing wrong? I consider using a network sniffing tool to see the differences…

Problem courtesy of: Per Erik Gransøe

Solution

The json param expects a JavaScript object and request turns it into a JSON string for you.

Try removing the quotes from around it like so:

var request = require('request');

request.post({
    'uri': 'http://[The Url]/[The Service].asmx/[The Operation]',
    'json': {"callbackcontextkey":"[the context key]",[The set of json formatted key/value pairs] },
    'headers': { }
}, function(e, r, body) {
    console.log("Response error: %j", e);
    console.log("Response r: %j", r);
    console.log("Response body: %j", body);
});

Alternatively, you could keep it as a string and set the body param instead of json and it would probably work that way too. More details here: https://npmjs.org/package/request

Solution courtesy of: Nathan Friedly

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *