How to access the body after a get request() in nodeJs - json

I have tried to use JSON.parse and request.on modules but none of the examples I have seen has helped me much. Can you send me an example of accessing "body" to create an array (parsing to JSON)? I'm a newbie in nodeJs.
Thank you in advance!
var request = require("request");
var options = { method: 'GET',
url: 'URL with credentials and filter',
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

Related

I want to parse an url to html

I want to parse an url to html then to use it. For this, I use axios but I get the following error:
Request failed with status code 500
My code:
import axios from 'axios';
export default async function parseHtml() {
const url = 'http://www.ameli.fr/accueil-de-la-ccam/telechargement/index.php';
let response;
try {
response = await axios({
method: 'get',
url: url,
});
} catch (error) {
throw error.message;
}
console.log(response.data);
}
Any idea please, I try also to use jsdom, htmlparse but I don't get any result
That url seems to be sending back a 500 error incorrectly (or it appears so).
You can ignore this error (something you wouldn't normally do!) using the validateStatus property like so:
async function parseHtml() {
const url = 'http://www.ameli.fr/accueil-de-la-ccam/telechargement/index.php';
let response;
try {
response = await axios({
url,
method: 'GET',
// Ignore failing HTTP status codes
validateStatus: status => true
});
console.log("Response status code:", response.status);
console.log("Response data:", response.data);
} catch (error) {
console.log(error.message);
}
}
This will give you the html data, which you can then parse.

Get json with headers by using nodejs

How can I get objects from JSON with headers and send an HTTP get a request to a link?
setHeader('header1', 'header1_value') for http://getsomejson.com/json.php
and retrieve data then send them to
randomlinktosenddata.com
You could use a library like request
try this code:
var request = require('request');
var options = {
url: 'http://getsomejson.com/json.php ',
headers: {
'Some-header': 'header-value'
}
};
request(options, (error, response, body) => {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
// use data
request({url:'randomlinktosenddata.com'} , (error,response,body) => {
// do more stuff...
});
}
});
you can install the request library by doing npm install request
Check this link: https://github.com/request/request
hope this helps

Firebase Function Error - Error: could not handle the request

const functions = require('firebase-functions');
const request = require('request');
exports.sendtest = functions.https.onRequest((requests, responses) => {
var id = 'test';
var num = 'test';
url='https://myurl.com/test.php?id='+id+'&num='+num;
request({
url: url,
method: 'get',
}, function (error, response, body) {
if (error) throw error;
response.redirect(body);
});
});
When I deploy and run the code I am getting error like
Error: could not handle the request
I don't know why I am getting such error.
This is because plan is free one. So it doesn't allow to connect outside google server.

I'm not using Express, but I'm trying extract POST data then to send a json as response, with no luck

I'm still very new to node.js so please bear with me.
I'm trying to extract POST data then sent a json as response, but I don't seem to be able to extract the data from the POST request and even worse I can't find the syntax for people who are NOT using Express to send the json. It keeps telling me res.json is not a function.
EDIT: I found out the problem for the json part, I was a dump. I finally remember what I was told, json are sent like strings.
var http = require('http');
var qs = require("querystring");
server = http.createServer(function (req, res) {
try {
var body = "";
var post = qs.parse("");
if (req.method == "POST") {
res.writeHeader(200, {"Content-Type": "application/json"});
req.on("data", function (data) {
body += data;
console.log(data); //It gives something like <Buffer xx xx xx ...>
if (body.length > 1e6)
req.connection.destroy();
});
req.on("end", function () {
post = qs.parse(body);
console.log(post.test); //It gives "undefined"
});
res.end(JSON.stringify({ a: 1 }));
} catch(err) {
console.dir(err);
res.writeHeader(200, {"Content-Type": "text/plain"});
res.end("Hi hi");
}
});
server.listen(8000);
console.log("http start #8000");
Any help? Thanks in advance.
below solves the date to string (i.e. converting buffer to string
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// console.log(textChunk); // will give you a stream of text from data
});
you could store textChunk out of the ondata handler, to then use that if required (say returning relevant data to the user back again)

JSON object from HTTP response there but undefiend

In Node.js, I use request to post as such:
First I make the options
var ops = {
'user':'johnny',
'password':'password'
};
Then I make the request as such:
request.post({url: endpoint, formData: ops}, function(err, res, body){
console.log(res.body);
});
This then returns the data I want from an API:
{"user":"johnny","time":"2016-11-03T15:58:34.444Z"}
But then when I change the request to:
request.post({url: endpoint, formData: ops}, function(err, res, body){
console.log(res.body.user);
});
I get back "undefined".
Why can I access the res.body but not then then res.body.user when user is clearly an attribute of the object?
Thanks
Your response being a string, this will do the trick :
var data = JSON.parse(res.body);
console.log(data.user);