Remote HTTP get JSON data - node.js

My client posted data from one website to my website using npm request module.
ie as follows.
testservice : function(req , res){
var data = { title : 'my title' , content : 'my content'};
request.post('https://dev.example.com/test' , data , function(err , response ,body){
if (err) console.log(err);
if(response) console.log('statuscode='+response.statuscode);
});
};
I tried to get the JSON data posted to my site from my client's site using request get method , but i didnt get json data output.
Please help me out to get JSON data which is posted using request post method. Thanks.

Try this:
testservice: function(req, res) {
var data = { title: 'my title', content: 'my content' },
options = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
};
request.post('https://dev.example.com/test', options, function(err, response, body) {
if (err) console.log(err);
if (response) console.log('statuscode=' + response.statuscode);
});
};

I tried to get the JSON data posted to my site from my client's site using request get method, but i didnt get json data output.
I believe you may be misunderstanding the request.get function. It doesn't "get" the data that was posted to your site, it in fact fires a "get" request off to a particular URL.
If you want to receive data on your site that was POST'ed, then you need to configure your server to listen for POST requests from your friends site and then parse out the posted data from the body of that request.
i.e. in your server code if you're using raw node.js
http.createServer(function(req,res){
if(req.method.toUpperCase() === "POST"){
//code to parse out the data from the post request
}
}).listen(8080)
For more detailed info on parsing out the POST'ed data, see How do you extract POST data in Node.js?
Let me know if this helps, please clarify your question if not.

Related

Node.js? API Authentication problems

This is what my "dev" sent me. Someone help please
I'm trying my best, but their API doesn't respond to our methods. This authentication is the root of the problem. I'm right now using Axios(the most popular and only method for making API requests for web apps) but it's not accepting request
and then i told him i would ask for help*
You can ask this question- ` How do I make requests for creating order API in my express app? I've tried to make the request by getting my form data from my EJS form using the request.body. But still, it is saying error 400.
Here is his code:
app.post('/order-labels', checkAuthenticated, (req, res) => {
const data = JSON.stringify(req.body);
console.log(data)
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
})
by console.logging we are getting the data, but the API doesn't accepting
The API Docs are here.
you may need an account to view just put junk
The API calls for url encoded string.
const data = JSON.stringify(req.body);
console.log(data)
data = new URLSearchParams(Object.entries(data)).toString();
console.log(data); // now should be URL encoded
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
See if the API likes the new encoding?

Axios post request body is just an empty object on the server side (React - Axios - Node.js - Express)

I was trying to send a post request to my server and was using this:
let dataToReturn = {
method: "POST",
url: "http://localhost:9000/logData",
headers: { "testing" : "IT WORKED" },
body: {"hola" : 'testing to see if this counts'}
}
axios(dataToReturn)
It know it would send. I checked the network tab in inspector and could see that it was sent, and could do req.headers on the server and it would print out the headers. But whenever I tried to log req.body on the server it would just print out '{}'
var body = {
firstName: 'testName',
lastName: 'testLastName'
};
axios.post('http://localhost:9000/logData', body)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
This works tho ^^ and successfully prints out the body when I do 'req.body'
Why does the top example log an empty object?
Here's what the route looked like on the server side
app.post('/logData', function(req, res) {
console.log('recieved post');
console.log(req.body);
res.sendStatus(200);
})
I acknowledge that I'm a noob and this might be a dumb question, so please excuse my ignorance. Also happy to post more info if you need it.
You need to add content type in the header of your request.change your header as mentioned below
headers: { "testing" : "IT WORKED","Content-Type":"application/json" },

Post request with Node fails but works with Python

I'm trying to use a sentiment analysis API for some tweets I've streamed. The API in question is this: http://sentiment.vivekn.com/docs/api/. I've done this before in Python before and it worked as expected. I made a post request using the requests library and sent a JSON object with my content. The JSON object looked something like this:
{
"txt": "The content of the tweet."
}
In Python, sending the post request looked something like this:
url = "http://sentiment.vivekn.com/api/text/"
data_dict = {
"txt": "hi"
}
r = requests.post(url,json.loads(json.dumps(data_dict)))
print(r.text)
Now I'll admit I'm new to Javascript and web based programming in general, but I assume the logic should be similar in both languages. I tried using the XMLHttpRequest method but it always returned an internal server error with status code: 500.
The website works, it takes post requests and responds with the analysis, but I can't get it to work with Node. This is what I'm working with in Javascript:
const rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://sentiment.vivekn.com/api/text/',
body: {
"txt": "This is a very negative sentence, so we should get a negative analysis!"
},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
console.log("Request received");
console.log(parsedBody);
})
.catch(function (err) {
console.log("Something went wrong\n" + err);
});
It always catches an error with status code 500. I've tried several other methods including making the request with XMLHttpRequest. Nothing seems to work. It would be great if someone could point out where I'm going wrong.
This isn't an answer, but I thought it useful to show some code that evokes a different response, which may be a clue that will help debug the problem.
I get the same response with curl:
jim-macbookpro:~/development/node/so$ curl -X POST 'http://sentiment.vivekn.com/api/text/' -H "Content-Type: application/json" -d '{"txt": "hi"}'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in theapplication.</p>
I changed the example to use 'node-fetch', and I don't get 500, rather I get 405 - METHOD NOT ALLOWED.
My suspicion is that this is a problem with the server being somehow very particular about the format of the request.
I hope this helps.
const fetch = require('node-fetch');
fetch('http://sentiment.vivekn.com/api/text', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
txt:
'This is a very negative sentence, so we should get a negative analysis!'
})
})
.then(function(parsedBody) {
console.log('Request received');
console.log(parsedBody);
})
.catch(function(err) {
console.log('Something went wrong\n' + err);
});

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

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

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();
}

Resources