How to do a simple read POST data in Node JS? - javascript

I've used this code to read the querystring ?name=Jeremy ...can anyone tell me how to do this with post data? also with json?
var http = require('http'), url = require('url');
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = url.parse(request.url, true);
response.write("Hello " + urlObj.query["name"] + "!\n");
}).listen(8000);
thanks!

You have to handle data and end events of http.ServerRequest object. Example:
var util = require("util"),
http = require('http'),
url = require('url'),
qs = require('querystring');
...
// this is inside path which handles your HTTP POST method request
if(request.method === "POST") {
var data = "";
request.on("data", function(chunk) {
data += chunk;
});
request.on("end", function() {
util.log("raw: " + data);
var json = qs.parse(data);
util.log("json: " + json);
});
}
Here is an article on this topic with example (with too old version of node.js so it might not work, but the principle is the same).

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)

Using request.on() for GET requests

When dealing with GET requests, should I be using request.on()?
For instance, in my main.js,
var http = require('http');
var dispatcher = require('./public/javascript/dispatcher.js');
var serverPort = 8124;
http.createServer(function (request, response) {
dispatcher.deal(request, response);
}).listen(serverPort);
and in dispatcher.js, I have
module.exports = {
deal: function(request, response) {
if(request.method === "GET") { // WITHIN THIS BLOCK
var get = require('./get.js');
// Pass data to the appropriate function
get.do(request, response);
} else if(request.method === "POST") {
var qs = require('querystring');
var requestBody = '';
request.on('data', function(data) {
requestBody += data;
});
request.on('end', function() {
var formData = qs.parse(requestBody);
var post = require('./post.js');
// Pass data to the appropriate function
post.doing(request, response, formData);
});
}
} // End deal
} // End exports
So to expand on my initial question and the code I've posted, the program works fine without the request.on(). My guess is that since there's no data to wait for from a GET request, there's no need for a require.on('end', ...). Any clarifications, recommendations, or suggestions are welcome!

CryptoJs is not decrypting URL on my NodeJS server

I am forwarding API calls from my frontend to my backend. I encrypt the API calls using CryptoJS.AES using the passphrase 'somekey'.
My relevant client code is...
var host = 'http://localhost:3000'
$('.send-button').click(function(){
var request = $('.request-input').val();
var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
console.log(encryptedRequest.toString())
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
console.log('Decrypted Request: ' + decryptedRequest.toString());
handleRequest(encryptedRequest.toString());
});
var handleRequest = function(request){
$.ajax({
type: "GET",
url: host + '/requests?call=' + request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
editor.setValue(rawJSON);
},
dataType: 'json'
});
}
relevant server side code is...
var port = 3000;
var serverUrl = "127.0.0.1";
var http = require("http");
var path = require("path");
var fs = require("fs");
var express = require("express");
var CryptoJs = require("crypto-js");
var app = express();
app.get('/requests', function(req, res) {
console.log('REQUEST: ' + req);
var call = req.query.call;
console.log(call)
console.log("To send: " + CryptoJs.AES.decrypt(call, 'somekey'));
});
The problem I keep getting is that it that when I decrypt it it either doesn't get the original URL and instead returns a bunch of jibberish. An example of this is...
Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN
Decryption: 68747470733a2f2f6e6577736170692e6f72672f76312f61727469636c6573
OR... It just returns nothing and appears blank.
Ideally I would like something like this.
Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN
Decryption: https://newsapi.org/v1/articles
Can anyone see what I am dong wrong?
Here is a working jsfiddle:
https://jsfiddle.net/5Lr6z4zp/1/
The encryption results in a Base64 string, while the decrypted string is Hex. To get back the “Message” you need to convert that to Utf8: decryptedRequest.toString(CryptoJS.enc.Utf8)
Here is the relevant part of the code that works:
var request = "testing decryption";
var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
console.log(encryptedRequest)
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
var decryptedMessage = decryptedRequest.toString(CryptoJS.enc.Utf8)
console.log('Decrypted Request: ' + decryptedMessage);
Here is a link for a resources that explains the encryption/decryption in more detail:
http://www.davidebarranca.com/2012/10/crypto-js-tutorial-cryptography-for-dummies/

Print received data from client in NodeJS server

I have a simple html file containing that piece of javascript:
<script type="text/javascript">
$.ajax({
url: 'http://192.168.X.X:8080',
data: '{"data": "1"}',
dataType: "jsonp",
cache: false,
timeout: 5000,
success: function(data) {
var ret = jQuery.parseJSON(data);
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
document.getElementById("error").innerHTML = 'Error: ' + error.message;
}
});
</script>
I simply want my NodeJS server to print data received (there: the number 1°).
Here is my NodeJS code:
var http = require('http');
var s = http.createServer();
s.on('request', function(request, response) {
response.writeHead(200);
console.log('a: '+request.method);
console.log('b: '+request.headers);
console.log('c: '+request.url);
});
s.listen(8080);
Server is receiving requests just find but how to retrieve the value of the data sent?
I just want server to receive a number from client and print it. How to do that?
Many thanks1
I think this does what your looking for.
#!/usr/bin/node
var http = require('http');
var s = http.createServer();
s.on('request', function(request, response) {
response.writeHead(200);
console.log('a: '+request.method);
console.log('b: '+request.headers);
console.log('c: '+request.url);
var url = decodeURIComponent(request.url);
var startPos = url.indexOf('{');
var endPos = url.indexOf('}');
var jsonString = url.substring(startPos, endPos+1);
json = JSON.parse(jsonString);
console.log(json['data'])
});
s.listen(8080);
If you just want to see jsonp works using the http module, you could use something like that (I wouldn't advise using this in any of your code, it's just for the demonstration):
var http = require('http');
var querystring = require('querystring');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var query = querystring.parse(req.url.split('?')[1]);
console.log(query);
res.end(query.callback + '({"Name": "Foo", "Id": 1234, "Rank": 7})');
}).listen(8080);
Note: when using jquery jsonp data should better be an object, not a string (see https://learn.jquery.com/ajax/working-with-jsonp/)
You should, however, ask yourself:
Why jsonp?
Is there a module that does all that for you & parse JSON, help you with errors/authentication/etc? I usually use https://www.npmjs.com/package/hapi (It supports jsonp if you really need it), there other modules like express.

Nodejs output -Domain name not found

Technically this is my first try in nodejs and frankly I am not sure if I am doing it right. I am creating a local server that will stream the output from a distant server. However, when I run my code and I enter a URL in the browser, the program fails with the following message:
events.js:45
throw arguments[1]; // Unhandled 'error' event
^
Error: ENOTFOUND, Domain name not found
at IOWatcher.callback (dns.js:74:15)
The URL I used was: 127.0.0.1:9000/http://www.yahoo.fr. And in the browser I had the following message:
No data received
Unable to load the webpage because the server sent no data.
Here are some suggestions:
Reload this web page later.
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
Any help is greatly appreciated.
Here is the code:
var base, dest, node_client,
count = 0,
url = require('url'),
util = require('util'),
http = require('http'),
http_client = require('http'),
request = require('request'),
events = require('events'),
httpProxy = require('./lib/node-http-proxy'),
data_emitter = new events.EventEmitter();
httpProxy.createServer(9000, 'localhost').listen(8000);
http.createServer(function (req, res) {
if(!count)
{
base = url.parse(req.url).pathname;
node_client = http_client.createClient(80, base);
count++;
} else {
dest = req.url.substr(1, req.url.length -1);
}
request = node_client.request("GET", dest, {"host": base});
request.addListener("response", function (response) {
var body = "";
response.addListener("data", function (data) {
body +=data;
});
response.addListener("end", function () {
var out = JSON.parse(body);
if(out.length > 0) {
data_emitter.emit("out", out);
}
});
});
// request.close();
var listener = data_emitter.addListener("data", function(out) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(JSON.stringify(out));
res.close();
});
}).listen(9000);
Wild guess : your browser automatically requests 127.0.0.1:9000/favicon.ico and your program then tries to resolve favicon.ico which obviously fails and makes your program crash before it can send any data for the real request.
Why such tangled code?
This is a scenario where it makes sense to avoid nested callbacks, and use named functions. If you refactor the code, then people are more likely to be help you.
Can you do console.log(out) in your listener callback? Let us know if Node.js has any response data to return.
Well, for any newbie like me in this area, here is how I solved it. It's not clean and can be implemented in better way. Feel free to change, give suggestions.
Code:
var url = require('url'),
http = require('http'),
request = require('request'),
httpProxy = require('./lib/node-http-proxy'),
des = '',
util = require('util'),
colors = require('colors'),
is_host = true;
httpProxy.createServer(9000, 'localhost').listen(8000);
var server = http.createServer(function (req, res) {
var pathname = '';
if(is_host) {
dest = req.url.substr(0, req.url.length -1);
pathname = dest;
is_host = false;
} else {
pathname = req.url.substr(0, req.url.length);
if(pathname.charAt(0) == "/") {
console.log('new request');
console.log(pathname);
pathname = dest + pathname;
}
}
console.log(pathname);
request.get({uri: pathname}, function (err, response, html) {
res.end(html);
});
console.log('fetched from ' + pathname);
});
server.listen(9000);

Categories

Resources