How to set JSON data in node.js response object? - node.js

I am using html on client side and my server side code is on node.js. I have some url's defined in to the nodejs application and I am calling them from my client html file. From node I am calling my REST application which is at another server. This rest application is written in Jersey java web services. I am able to call node.js from my html and from node code I am getting response from Jersey web service module. After receiving this response I am setting it to response object of node.js but this response is not available on html jquery ajax call.
$.ajax({
type :"POST",
dataType: 'json',
data: jsontest,
url: 'http://<code>localhost</code>:9999/hello',
success: function(data) {
console.log('success');
console.log(data);
console.log(data.id);
}, error : function(response) {
console.log(JSON.stringify(response));
}
});
Server side code:
var tmp = req;
var authentication = JSON.stringify(tmp.body.authenticationKey);
console.log("authentication :- "+authentication);
requestObj({
url : "http://<code>restserver</code>:port/restmodule/controller/hello",
method : "POST",
headers : { "Content-Type" : "application/json","pubKey":authentication},
body : JSON.stringify(tmp.body)
},
function (error, res, body) {
indexresponseBody = JSON.stringify(JSON.parse(body).message);
}
);
res.writeHead(200, {'content-type':'text/html'});
console.log("JSON returned from REST "+indexresponseBody);
res.write(indexresponseBody);
res.end();
I am able to get the json and this is printed on node server console. But when I am writing this json to the response(res) object on firebug console I am not able to see this json. Can anybody tell me how can I get this response.

Could be because of async nature of callback, try this -
function (error, resp, body) {
indexresponseBody = JSON.stringify(JSON.parse(body).message);
res.writeHead(200, {'content-type':'text/html'});
console.log("JSON returned from REST "+indexresponseBody);
res.write(indexresponseBody);
res.end();
}

Related

Paypal API call produces 415 status

I set up my express app to listen for Paypal webhooks of my sandbox app. Then I try to verify the integrity of the data via the verify-webhook-signature API endpoint. I use the request module for that. But all I get is a 415 Unsupported Media Type status code and an empty body. This is my code:
app.post('/webhooks', function (req, res) {
if (req.body.event_type == 'PAYMENT.CAPTURE.COMPLETED') {
headers = {
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Authorization' : 'Bearer <AUTH_TOKEN>'
}
// Get the data for the API call of the webhook request
data = {
'transmission_id': req.headers['paypal-transmission-id'],
'transmission_time': req.headers['paypal-transmission-time'],
'cert_url': req.headers['paypal-cert-url'],
'auth_algo': req.headers['paypal-auth-algo'],
'transmission_sig': req.headers['paypal-transmission-sig'],
'webhook_id': '41G05244UL253035G',
'webhook_event' : req.body
}
request.post({
url: 'https://api.sandbox.paypal.com/v1/notifications/verify-webhook-signature',
headers: headers,
form: data,
}, (error, response, body) => {
if (error) {
console.error(error)
return
}
console.log(response.statusCode);
});
}
res.sendStatus(200);
});
What is wrong with this data?
Edit: Changing 'form: data' to 'body: JSON.stringify(data)' did it.
Why are you sending back a form post? Don't post a form. Send back raw data.

calling external rest api from node without encoding querystring params

I am trying to call an external rest API from node server by using request node module.
let request = require('request');
var options = {
method: 'POST',
url: 'https://somerestURI:3000',
qs: { msg: 'some|data|for|other|server' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
If I try to run the above code, query string value is being encoded to
some%7cdata%7cfor%7cother%7cserver
as a result I am not receiving correct response.
But if I fire the same request in POSTMAN. I am receiving the expected output(I think postman is not encoding query string).
So what I want is don't encode the query string value.
Any help would be greatly appreciated.
As answered here, you can disable encoding in qsStringifyOptions
var options = {
method: 'POST',
url: 'https://somerestURI:3000',
qs: { msg: 'some|data|for|other|server' },
qsStringifyOptions: {
encoding: false
}
};
You can use node-rest-client package. It allows connecting to any REST API and get results as javascript Object.
var HttpClient = require('node-rest-client').Client;
var httpClient = new HttpClient();
// GET Call
httpClient.get("http://remote.site/rest/xml/method", function (data, response) {
// parsed response body as js object
console.log(data);
// raw response
console.log(response);
});)
or for POST Call
var args = {
data: { test: "hello" },
headers: { "Content-Type": "application/json" }
};
//POST Call
httpClient.post("http://remote.site/rest/xml/method", args, function (data, response) {
// parsed response body as js object
console.log(data);
// raw response
console.log(response);
});

How to get response header in node.js

I'm working on a nodejs project, I use request module to submit restful request and get response. (here is the module link: https://github.com/request/request)
Following the instruction, I should be able to get the response header by calling response.headers[''], however, seems it doesn't work, when I try to call var contentType = response.headers['Content-Type'], the contentType is undefined. (When I use postman, I could get Content-Type from the response). Anyone knows what's wrong?
This is the instruction from the site:
var request = require('request')
request(
{ method: 'GET'
, uri: 'http://www.google.com'
, gzip: true
}
, function (error, response, body) {
// body is the decompressed response body
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
In node, the headers are accessed by using lowercased names, so using response.headers['content-encoding'] is correct.
Your code snippet currently works for me and displays 'server encoded the data as: gzip.'

node-soap request is sending null parameters

I've been trying to use node-soap library for nodejs to consume a soap service but when i send my request the response from the service is that flightNumber in my request is null.
I Also tried sending the same request that works for me in soap UI in xml format and i got the same error message.
This is my request:
var request = {
"body" : {
"DisplayFlightLegsRQ": {
"flightNumber": "222",
"airlineCode": "BB",
"departureIATACode": "MIA"
"flightDate": {
"departureDateCondition": "SCHEDULE",
"requestTimeStandard": "UTC",
"departureDate": "10-10-2015"
}
}
},
"headers": {"Content-Type": "text/xml;charset=UTF-8"}
}
Call to the soap service:
soap.createClient(url,function(err, client){
client.addHttpHeader('App-name', 'fs');
client.setSecurity(new soap.BasicAuthSecurity('***', '***'));
client.displayFls(request, function(err, result, body) {
console.log(result.body);
parseString(body, function(err, result){
var requestResult = result['SOAP-ENV:Envelope']['SOAP-ENV:Body'][0].DisplayFlightLegsRS[0].return[0];
console.log(requestResult);
})
});
});
is it possible that there is an issue in this soap-node library causing my request to send null parameters? I debugged the request just before being sent and the object is well formatted and it has all the values. Maybe this library is doing an inside transformation from the json request to xml and in that process is erasing the values? or maybe my request is missing something.
I appreciate any help.
Thanks :)

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

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...
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

Resources