how to parse a request in a node.js server built on net module - parsing

We are building a server with net module, and having hard time extracting the URL (and resource path) from the request. The following code crashes, saying:
Parameter 'url' must be a string not undefined.
File netServer.js:
var net = require('net');
var url = require('url');
var server = net.createServer(function(socket) { //'connection' listener
socket.on('connect', function(request) {
});
socket.on('data', function(request) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
});
socket.on('end', function() {
});
});
server.listen(8080, function() { //'listening' listener
console.log('server bound');
});
Any suggestions?

Are you trying to build an HTTP server? net is a TCP package, so all you get is the remoteAddress and remotePort, the rest will be sent on the data handler (which is just passed a Buffer, or a string, depending on the encoding).
Use the HTTP module for this, because it does all of the parsing for you.

Related

node.js - The first argument must be of type string or an instance of Buffer with http module

these day I'm new to node.js and leanrning them from Youtube vid
I had a plan to express image file to webbrowser
here is something wrong (I've already add image file in my folder)
and then I was trying to resolve this problem by searching google
but I hadn't found out.
It's first time to make a new account
it's the code
var http=require('http');
var fs = require('fs');
var server = http.createServer();
var host = '192.168.0.42';
var port = 3000;
server.listen(port,host,50000,function(){
console.log('웹서버 실행됨');
});
server.on('connection',function(socket){
var addr = socket.address();
console.log('클라이언트가 접속했습니다. : %s, %d', addr.address,addr.port);
});
server.on('request',function(req,res){
console.log('클라이언트 요청이 들어왔습니다.');
var filename = "coronavirus.png";
fs.readFile(filename, function(err,data){
res.writeHead(200, {"Content-Type":"image/png"});
res.write(data);
res.end();
});
});
your readFile needs to include an absolute or relative path.
try with a forward "/" as in /your_file_path or resolve with a cross-platform solution using __dirname + your file_path.
From the docs
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});

React-Native Websocket Event data property is missing

I am trying to connect to the Watson TTS API over a Websocket connection in React-Native. The connection is established and I can send a message to the server, however the data that I get back from the server somehow always is empty.
It seems as if the event.data property is completely missing. If I log it to the console in react-native I get 'undefined' as a result. If i use the same code in the browser everything works perfectly.
I am using react-native 0.33 and here's my code:
function connectTTS(token) {
var voice = "de-DE_BirgitVoice";
var format = 'audio/basic';
var token = token;
var wsURI = "wss://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=" + voice + "&watson-token=" + token;
function onOpen(evt) {
var message = {
text: "Hello world.",
accept: format
};
// note: the Text to Speech service currently only accepts a single message per WebSocket connection
websocket.send(JSON.stringify(message));
}
var audioParts = [];
var finalAudio;
function onMessage(evt) {
console.log(evt.data);
if (typeof evt.data === 'string') {
console.log('Received string message: ', evt.data)
} else {
console.log('Received ' + evt.data.size + ' binary bytes', evt.data.type);
audioParts.push(evt.data);
}
}
function onClose(evt) {
console.log('WebSocket closed', evt.code, evt.reason);
console.log(audioParts);
console.log(format);
finalAudio = new Blob(audioParts, {type: format});
console.log('final audio: ', finalAudio);
}
function onError(evt) {
console.log('WebSocket error', evt);
}
var websocket = new WebSocket(wsURI);
websocket.onopen = onOpen;
websocket.onclose = onClose;
websocket.onmessage = onMessage;
websocket.onerror = onError;
}
It would be great if somebody with more react-native / websocket experience could help me find the solution. Thanks.
In react-native up to 0.53 (latest version at the moment), react-native WebSocket event processing relies on event-target-shim 1.1.1 lib which wraps an event and does not include data to the wrapped event, so in order to get WebSocket event data you may use one of two approaches:
Get data from __proto__;
Rewrite event-target-shim 1.1.1;
The first approach:
use <your event>.__proto__.__proto__.data
The second approach:
fork event-target-shim and reset to event-target-shim 1.1.1;
fork react-native;
Add the code listed below to the event-target-shim/lib/event-wrapper.js;
rewrite react-native package.json to use forked version of the event-target-shim;
rewrite package.json of your project;
Code to add in exports.createEventWrapper after var propertyDefinition = {...}:
if (event.type === "message"){
propertyDefinition.data = {value: event.data, enumerable: true};
}

Meteor - Parse Data from Incoming HTTP Request

For outgoing HTTP requests (using meteor.http.call) I can define params and/or data. The results are then available (via results.content).
How do I access and parse the body/contents/data of incoming HTTP requests?
Using iron-router, I have got as far as this:
Router.map(function () {
this.route('httpTest', {
path: '/httpTest',
action: function () {
var request = this.request;
var response = this.response;
console.log('request_body: '+ request.body);
// request.body does not work. what should it be????
N.B. I understand that I CAN access query parameters, but I want to access form data and/or json data from the body of an incoming http request.
The request is an incoming http message, which is a Readable Stream, so you can get the data of the request by reading from that stream.
The following should work (but I haven't tested it):
var readable = this.request;
var alldata = "";
readable.on('data', function(chunk) {
alldata += chunk;
})
readable.on('end', function() {
console.log('do something with alldata');
});
It may not be working because of the missing where: 'server'. Here is a working example:
Router.map(function() {
this.route('test', {
where: 'server',
action: function() {
console.log(this.request.body.make);
console.log(this.request.body.model);
this.response.writeHead(200, {'Content-Type': 'text/html'});
this.response.end('hello!\n');
}
});
});
From the command line I can hit this route with:
curl -X POST -H "Content-Type: application/json" -d '{"make":"honda","model":"civic"}' http://localhost:3000/test
Which prints the expected honda and civic in the server's terminal. It looks like this.request.body is already parsed so you can access any variables directly which is nice if your input is json.
To read the raw body, without having Node.js JSON-ify it, in a synchronous way, I used this:
Router.route("my/api", function() {
var rawBody = "";
var chunk;
while ((chunk = this.request.read()) !== null) {
rawBody += chunk;
}
}, { where: "server" });
(the asynch way proposed in another answer here didn't worked for me, although it should as per Node.js documentation).

How to parse a XML string in a Firefox addon using Add-on SDK

I am trying to create a FF AddOn that brings some XML data from a website. But I can't find a way to parse my RESPONSE. First I used DOMParser but I get this error:
ReferenceError: DOMParser is not defined.
Someone suggested to use XMLHttpRequest, because the parsing is done automatically but then I get this other error:
Error: An exception occurred. Traceback (most recent call last):
File
"resource://jid0-a23vmnhgidl8wlymvolsst4ca98-at-jetpack/api-utils/lib/cuddlefish.js",
line 208, in require
let module, manifest = this.manifest[base], requirer = this.modules[base]; TypeError: this.manifest is undefined
I really don't know what else to do. I must note that I am using the AddOn Builder to achieve this.
Below the code that doesn't seem to work.
Option 1:
exports.main = function() {
require("widget").Widget({
id: "widgetID1",
label: "My Mozilla Widget",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function(event) {
var Request = require("request").Request;
var goblecontent = Request({
url: "http://www.myexperiment.org/search.xml?query=goble",
onComplete: function (response) {
var parser = new DOMParser();
var xml = parser.parseFromString(response.text, "application/xml");
var packs = xml.getElementsByTagName("packs");
console.log(packs);
}
});
goblecontent.get();
}
});
};
Option 2:
exports.main = function() {
require("widget").Widget({
id: "widgetID1",
label: "My Mozilla Widget",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function(event) {
var request = new require("xhr").XMLHttpRequest();
request.open("GET", "http://www.myexperiment.org/search.xml?query=goble", false);
request.send(null);
if (request.status === 200) {
console.log(request.responseText);
}
}
});
};
DOMParser constructor isn't defined in the context of SDK modules. You can still get it using chrome authority however:
var {Cc, Ci} = require("chrome");
var parser = Cc["#mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
nsIDOMParser documentation.
That said, your approach with XMLHttpRequest should work as well. You used the new operator incorrectly however, the way you wrote it a new "require object" is being created. This way it should work however:
var {XMLHttpRequest} = require("xhr");
var request = new XMLHttpRequest();
Please consider using an asynchronous XMLHttpRequest object however, use request.onreadystatechange to attach your listener (the xhr module currently doesn't support other types of listeners or addEventListener).
If you use XMLHttpRequest (available via the xhr module) you can easily avoid the use of DOMParser. Bellow I provide an example supposing request is an XMLHttpRequest object which request is successfully completed:
Instead of:
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(request.responseText, "application/xml");
Use:
var xmlDoc = request.responseXML;
An then you can:
var packs = xmlDoc.getElementsByTagName("packs");
console.log(packs);
Or whatever.

two way communication between extension and content javascript files

i am trying to accomplish a two way communication request response in my firefox sidebar extension, i have a file named event.js this resides on the content side, i have another file called sidebar.js file which is residing in the xul. I am able to communicate from event.js to sidebar.js file using the dispatchEvent method. my event in turn raises a XMLHttpRequest in sidebar.js file which hits the server and sends back the response. Now, here i am unable to pass the response to the event.js file. I want the response to be accessed in the event.js file. Till now i have achieved only one way communication. Please help me in getting the two way communication.
Code is as follows:
// event.js file
// This event occurs on blur of the text box where i need to save the text into the server
function saveEvent() {
var element = document.getElementById("fetchData");
element.setAttribute("urlPath", "http://localhost:8080/event?Id=12");
element.setAttribute("jsonObj", convertToList);
element.setAttribute("methodType", "POST");
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("saveEvent", true, true);
element.dispatchEvent(evt);
//Fetching the response over here by adding the listener
document.addEventListener("dispatchedResponse", function (e) { MyExtension.responseListener(e); }, false, true);
}
var MyExtension = {
responseListener: function (evt) {
receivedResponse(evt.target.getAttribute("responseObject"));
}
}
function receivedResponse(event) {
alert('response: ' + event);
}
// sidebar.js file
window.addEventListener("load", function (event) {
var saveAjaxRequest = function (urlPath, jsonObj, methodType, evtTarget) {
var url = urlPath;
var request = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest);
request.onload = function (aEvent) {
window.alert("Response Text: " + aEvent.target.responseText);
saveResponse = aEvent.target.responseText;
//here i am again trying to dispatch the response i got from the server back to the origin, but unable to pass it...
evtTarget.setAttribute("responseObject", saveResponse);
document.documentElement.appendChild(evtTarget);
var evt = document.createEvent("dispatchedRes"); // Error line "Operation is not supported" code: "9"
evt.initEvent("dispatchedResponse", true, false);
evtTarget.dispatchEvent(evt);
};
request.onerror = function (aEvent) {
window.alert("Error Status: " + aEvent.target.status);
};
//window.alert(methodType + " " + url);
request.open(methodType, url, true);
request.send(jsonObj);
};
this.onLoad = function () {
document.addEventListener("saveEvent", function (e) { MyExtension.saveListener(e); }, false, true);
}
var MyExtension =
{
saveListener: function (evt) {
saveAjaxRequest(evt.target.getAttribute("urlPath"), evt.target.getAttribute("jsonObj"), evt.target.getAttribute("methodType"), evt.originalTarget);
}
};
});
Why are you moving your fetchData element into the sidebar document? You should leave it where it is, otherwise your content code won't be able to receive the event. Also, use the content document to create the event. Finally, document.createEvent() parameter for custom events should be "Events". So the code after your //here i am again trying comment should look like:
evtTarget.setAttribute("responseObject", saveResponse);
var evt = evtTarget.ownerDocument.createEvent("Events");
evt.initEvent("dispatchedResponse", true, false);
evtTarget.dispatchEvent(evt);
Please note however that your code as you show it here is a huge security vulnerability - it allows any website to make any HTTP requests and get the result back, so it essentially disables same-origin policy. At the very least you need to check that the website talking to you is allowed to do it (e.g. it belongs to your server). But even then it stays a security risk because server response could be altered (e.g. by an attacker on a public WLAN) or your server could be hacked - and you would be giving an attacker access to sensitive data (for example he could trigger a request to mail.google.com and if the victim happens to be logged in he will be able to read all email data). So please make this less generic, only allow requests to some websites.

Resources