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
Related
I'm working on Protractor automation, where I need to save JSON after few activities in browser. Then I'm checking the length of the object but I have seen that no console or expect conditions are working when given in setTimeout.
The console and expect statements are working if not given in setTimeout but the JSON response is asynchronous even before the activities.
test_speck.js :
it('Verify the json', function () {
this.commonfunc.checkJSON();
}
common_functions.js :
checkJSON: function(){
setTimeout(function(){
var request = require('request');
request('https://jsonplaceholder.typicode.com/users', function (error, response, body){
if (!error && response.statusCode == 200){
var importedJSON = JSON.parse(body);
console.log('Length of importedJSON : ' + importedJSON.length);
expect(importedJSON.length).toBeGreaterThan(0);
}
}
},90000);
}
Actual : The spec is being passed without any console.log or expect statements.
Expected : Console and expect statments to be worked
Pass a callback and it should work.
describe('SO Question 58726564', () => {
it('Verify the json', (done) => {
var request = require('request');
request('https://jsonplaceholder.typicode.com/users', function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
console.log('Length of importedJSON : ' + importedJSON.length);
expect(importedJSON.length).toBeGreaterThan(10);
}
done()
})
})
})
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)
I would like to send an HTTPS POST from one nodeJS server to another. I have some JSON data I would like to send with this request (populated by a html form).
How can I do this? I am aware of https.request() but there does not seem to be an option to include JSON as a part of the query. From my research it seems possible with an HTTP request, but not an HTTPS request. How can I solve this?
const pug = require('pug');
var cloudinary = require('cloudinary');
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var request = require('request');
var bodyParser = require('body-parser');
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'GET'
};
var app = express();
var parser = bodyParser.raw();
app.use(parser);
app.set('view engine', 'pug');
app.get('/', upload.single('avatar'), function(req, res) {
return res.render('index.pug');
});
app.get('/makeRequest*', function(req, res) {
query = req['query'];
/*
Here, I would like to send the contents of the query variable as JSON to the server specified in options.
*/
});
You can send JSON data through a POST http request with the native https node module, as stated in the documentation
All options from http.request() are valid.
So, taking the http.request() example you can do the following:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
You should edit postData to your desired JSON object
I believe the below is what you want. Using the request library. See comments in the code for my recommendations.
...
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'POST',
json: true
};
...
//making a post request and sending up your query is better then putting it in the query string
app.post('/makeRequest', function(req, res) {
var query = req.body['query'];
//NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request.
//(you may need to make changes on your other servers)
options.body = { payload: query };
request(options, function(err, response, body) {
if (err) {
//Handle error
return;
}
if (response.statusCode == 200) {
console.log('contents received');
}
});
});
as matt mentioned you need to use request
to send JSON object not JSON.Stringify so that at the server you can receive it using:
app.post('/makeRequest', function(req, res) {
console.log (req.body.param1);
}
Use the following code:
var request = require("request");
request({
'url':"http://www.url.com",
method: "POST",
json: true,
body: {'param1':'any value'}
}, function (error, resp, body) {
console.log ("check response.");
});
I have javascript code that should login (ie send some information to the server) and then receive a reply JSON message. I know this is doable by first doing a post, and then in the asynchronous response, when it completes, do a get. This would require two callback functions and two messages.
I was just wondering whether there is any way to do a get and send JSON as part of the query, so that there is just a single request/response rather than two.
Here is a sample post I wrote:
function post(url, payload, callback) {
payload = JSON.stringify(payload);
var http = new XMLHttpRequest();
http.open("POST", location.pathname + url, true);
http.setRequestHeader("Content-type", "application/json");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status !== 200) {
callback(false, http.response);
} else if (http.readyState === 4 && http.status === 200) {
callback(true, http.response);
}
return;
};
http.send(payload);
}
If I want to get back JSON, what do I do?
Is it as simple as changing POST to GET and looking at:
http.responseText upon the return?
If you are doing any login functionality you should always use the HTTP POST method.
You could use AJAX (W3schools documentation about AJAX ) to handle sending your login form over POST and then handle the response in the same code block. bellow is an example.
$('#login-form').submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
// serializes the form data with id login-form
var formData = $(this).serialize();
$.ajax({
type: 'POST',
data: formData,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
url: $(this).attr('action'),
//if your server sends a status OK message handle the response
//data will be the JSON response from the server
success: function(result,status,xhr) {
var jsonRes = JSON.parse(result); // parse the JSON object
console.log(jsonRes);
},
//if there was an error with your request the server will send
// an error response code and it is handled here
error: function(xhr,status,error) {
console.log(error);
}
});
I got a strage response from my JSON call! This is my response output:
Console Output
And that's my JSON request:
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body)
}
})
I think it's something wrong about the charset, but i don't get how i can change this.
Solution:
// Had to decode url
var encoded = encodeURIComponent(name);
var url = "xxx" + encoded;
I've cleared a lot of misleading junk out of your code to get to the heart of the problem.
This now reproduces the original issue:
var request = require('request');
getItemPrice("StatTrakā¢ UMP-45 | Delusion (Minimal Wear)")
function getItemPrice(market_hash_name, callback) {
var url = "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=" + market_hash_name;
request({
url: url,
json: true
}, function(error, response, body) {
console.log(body);
if (!error && response.statusCode === 200) {
console.log(parseFloat(((body.lowest_price).replace(/\,/g, '.')).split('&')[0]));
}
})
}
Your problem is that what you are calling is not a valid URL and the server is reacting to it badly.
You must encode special characters into the URL format:
var url = "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=" +
encodeURIComponent(market_hash_name);
What kind of REST API do you call? If it's node js API, you can set the charset there
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
And if that is not the case, set the request charset like this
request.setHeader('Accept-Charset', 'UTF-8)