POST request with data in node.js - javascript

How could I send POST request with data (eg. some variables) to the https server and display the results to the end user?

Use the http.Client module. From the docs:
var http = require('http');
var google = http.createClient(80, 'www.google.com');
var request = google.request('GET', '/', {'host': 'www.google.com'});
request.end();
request.on('response', function (response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
I am pretty sure that you can exchange GET with POST ;)

Related

eBay API CORS request using JavaScript returns undefined

I want to fetch JSON data from eBay Sandbox using JavaScript
I tried getting it through CORS request (as it is a cross domain request) but it returns undefined. I tried lots of different code but I haven't found any solutions.
What I want to do is that fetch the products from eBay and display them in my Chrome extension.
Any help is appreciated.
You can send a GET request to the URL.
const http = require('http');
let url = 'http://svcs.sandbox.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=NiraliAc-FlashSal-SBX-7d56b4536-d82a9262&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=harry%20potter&paginationInput.entriesPerPage=3&itemFilter(0).name=MaxPrice&itemFilter(0).value=25&itemFilter(0).paramName=Currency&itemFilter(0).paramValue=USD&itemFilter(1).name=FreeShippingOnly&itemFilter(1).value=true&itemFilter(2).name=ListingType&itemFilter(2).value(0)=AuctionWithBIN&itemFilter(2).value(1)=FixedPrice&itemFilter(2).value(2)=StoreInventory';
http.get(url, res => {
let body = '';
res.on('data', data => body += data);
res.on('end', () => {
console.log(body);
});
});
I found a solution by making a CORS request and using the CORS Anywhere API from https://github.com/Rob--W/cors-anywhere/
var cors_api_url = 'https://cors-anywhere.herokuapp.com/';
function doCORSRequest(options, printResult) {
var x = new XMLHttpRequest();
x.open(options.method, cors_api_url + options.url);
x.onload = x.onerror = function() {
printResult(
options.method + ' ' + options.url + '\n' +
x.status + ' ' + x.statusText + '\n\n' +
(x.responseText || '')
);
};
x.send(options.data);
}
(function() {
var outputField = document.getElementById('output');
new1();
function new1() {
// e.preventDefault();
doCORSRequest({
method: 'GET',
url: url,
}, function printResult(result) {
//result contains the response
//write your code here
});
};
})();
Source: https://github.com/Rob--W/cors-anywhere/blob/master/demo.html
(Live example: https://robwu.nl/cors-anywhere.html)

can we modify fs.readFileSync(__dirname + '/index.html');?

Can we modify fs.readFileSync(__dirname + '/game.php'); to fs.readFileSync(__dirname + '/game.php?id='+id); ?
It gives me an error:
fs.js:549 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
Is there any other way?
I suppose you're trying to do a GET call to your php service, which runs on its own (like you have a webserver which provides php pages on localhost/game.php or similar).
If this is the case, you need to use the http library, and I think something like this can work for you:
"use strict";
var http = require("http");
var id = 123;
var options = {
host: "localhost",
port: 80,
path: 'game.php?id=' + id,
method: "GET"
};
var req = http.request(options, function(res) {
console.log("STATUS: " + res.statusCode);
console.log("HEADERS: " + JSON.stringify(res.headers));
res.on("data", function (chunk) {
console.log("BODY: " + chunk);
});
});
req.end();

NodeJS: HTTP GET returns the code instead of JSON object

I have written the following NodeJS code to retrieve the json object from a website
var http = require('http');
var url = {
host: 'www.sample-website.com',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
},
};
http.get(url, function(obj) {
var output = "";
for (property in obj) {
output += property + obj[property] ;
}
console.log(output);
})
However as response I'm getting some code(some sort of events.js code) that I can't understand (not the HTML code). Need help figuring out where I'm going wrong
Including a snippet for reference ::
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
According to node.js API docs, http.get() passes a ServerResponse object to its callback. You're currently printing that object (and its parents') properties.
If you want to get the response body, you should register a listener on its data event:
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
and re-assemble the chunks.
Response code can be accessed via res.statuscode property and res.headers will give you the response headers in an array.
As requested, here's a full sample code:
var http = require('http');
var url = 'http://stackoverflow.com';
// ...
http.request(url, function (res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
console.log('BODY: ');
res.setEncoding('utf8');
res.on('data', function (chunk) {
process.stdout.write(chunk);
});
}).end();

Read raw http message in Nodejs

I'm sending an http request using the http.request function, and I would like to read the whole http response like text; that is, the raw http protocol text. Is it possible? I've written the below code but it's not working.
// Set up the request
console.log('Sending request');
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
console.log('Response statusCode: ' + res.statusCode);
// res.on('data', function (chunk) {
// console.log('Response: ' + chunk);
// });
// res.on('end', function() {});
});
post_req.on('socket', function (socket) {
var response = "";
socket.on('data', function(chunk){
console.log(chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
If you want access to the raw http message, I'd suggest using the net module instead, and writing the request yourself. Something like this for a simple GET request:
var net = require('net');
var host = 'stackoverflow.com',
port = 80,
socket = net.connect(port, host, function() {
var request = "GET / HTTP/1.1\r\nHost: " + host + "\r\n\r\n",
rawResponse = "";
// send http request:
socket.end(request);
// assume utf-8 encoding:
socket.setEncoding('utf-8');
// collect raw http message:
socket.on('data', function(chunk) {
rawResponse += chunk;
});
socket.on('end', function(){
console.log(rawResponse);
});
});
For a POST request sending application/x-www-form-urlencoded data, you could write the request using something like:
function writePOSTRequest (data, host, path) {
return "POST " + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + Buffer.byteLength(data) + "\r\n\r\n" +
data + "\r\n\r\n";
}
var data = "name1=value1&name2=value2",
request = writePOSTRequest(data, host, "/path/to/resource");
where I'm using Buffer.byteLength because Content-Length requires the length in bytes, not in characters. Also, remember that data must be URL encoded.
If you don't know much about the format of HTTP messages, then this is a decent place to start:
http://jmarshall.com/easy/http/
Also, if you don't know what the encoding of the response will be then you'll have to parse the headers first to find out, but UTF-8 is by far the most common so it's a pretty safe bet.
Streams2 and Streams1 not always able to inter-operate well, see "problem: streams1 and streams2 duality" in this video.
I tried to listen data at a bit lower level than streams and this code prints raw http response with headers for me:
var http = require('http');
var raw = '';
console.log('Sending request');
var req = http.request({host: 'stackoverflow.com'}, function(res) {
watch(res, 'res');
res.on('end', function() {
console.log(raw);
});
res.on('data', function(data) {
// if we don't attach 'data' handler here 'end' is not called
});
});
req.on('socket', function (socket) {
socket.resume();
var oldOndata = socket.ondata;
socket.ondata = function(buf, start, end) {
raw += buf.slice(start, end).toString();
oldOndata.call(socket, buf, start, end);
};
});
req.end();
Assuming these kind of tools are allowed in your environment, you could run up an HTTP debug proxy such as Fiddler http://www.fiddler2.com/, which enables you to inspect the HTTP calls and responses.

With node.js how to I set a var to response from HTTP client?

I know this is probably Asynchronous Javascript 101 and I do have some books on the Kindle I could consult, but I am nowhere near my device.
I have a node app with a variable being assigned to a module that I'm loading. The module has one function that downloads a string of data from a URL.
The problem is, how do I not set the variable until the request has returned?
My code looks like this:
Downloader.js:
var http = require('http');
exports.downloadString = function(str) {
console.log("Downloading from " + str);
http.get(str, function(res) {
var data = [];
console.log("Got response: " + res.statusCode);
res.on('data', function (chunk) {
data.push(chunk);
});
res.on('end', function() {
return data.join('');
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
app.js:
var downloader = require('./lib/Downloader')
, dateParser = require('./lib/DateParser')
, eventIdGenerator = require('./lib/EventIdGenerator');
var report = downloader.downloadString("http://exampleapi.com");
console.log(report);
I need to wait until the variable named "report" is populated.
Obviously this means my Mocha tests are also failing as I'm still unsure of how to tell the test to wait until the variable is filled.
I'm sure this is extremely simple, but I am drawing a blank!
Thanks!
Node.js is (mostly) asynchronous, so you'd need to pass a callback function to your module:
Downloader.js:
var http = require('http');
exports.downloadString = function(str, callback) {
console.log("Downloading from " + str);
http.get(str, function(res) {
var data = [];
console.log("Got response: " + res.statusCode);
res.on('data', function (chunk) {
data.push(chunk);
});
res.on('end', function() {
callback(data.join(''));
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
};
app.js:
var downloader = require('./lib/Downloader')
, dateParser = require('./lib/DateParser')
, eventIdGenerator = require('./lib/EventIdGenerator');
downloader.downloadString("http://exampleapi.com", function(report) {
console.log(report);
});

Categories

Resources