How to get entire request in node.js - javascript

I would like to get the entire request (header and body just as they appear when they arrive at the application) in Node.js. I'm able to get it by reading directly from the socket on connection (example below), but I haven't found a way to associate it with a particular request object as it's processed by the server.
...
var server = http.createServer(app).listen();
server.on('connection', function(socket) {
socket.on('data', function(data) {
console.log(data.toString());
});
});
...
app.get("/", function(req, res) {
//get the data that would be output from the above snippet in this context
//do something with it
});
This is just one example to illustrate what I'm looking for, I'm open to any method to achieve this other than attempting to reconstruct the request from information provided in the request object.

Related

I don't fully understand what app.get('/consult')

I am new to express and I still struggle with the meaning of app.get().
In my HTML page, I have a button with the id=consult-button.
I gave it the following script:
document.getElementById("consult-button").addEventListener("click", function() {
window.location.href = '/consulting';
});
On my app.js file, on the other hand, I have:
app.get('/consulting', (req, res) => {
const client = new pg.Client(config);
client.connect();
client.query('SELECT * FROM questionaire', (err, result) => {
if (err) {
console.log(err);
}
res.send(result.rows);
client.end();
});
});
Can someone help me understand this? Tell me if what I am writing is right:
when the button is clicked, a url with the name "consulting" is created. then app.get call on that url and sends the results of the query in that url?
When the user clicks on the button on the web page, the browser is going to send an HTTP GET request to the endpoint on the server (/consulting),
for example, if your website domain is www.example.com, the browser is going to send the request to www.example.com/consulting,
or if your domain is 192.168.1.50:3000 for example in case you're working on localhost for example, the website is going to send a request to 192.168.1.50:3000/consulting.
But this piece of code doesn't only send a request to the server, it also changes the URL to /consulting, (ex: www.example.com becomes www.example.com/consulting).
Now when the request travels from the website (the computer of the website visitor) to the back-end server (which is express in your case), express is going to catch this request in the following controller (it's called a controller)
app.get('/consulting', (req, res) => {
const client = new pg.Client(config);
client.connect();
client.query('SELECT * FROM questionaire', (err, result) => {
if (err) {
console.log(err);
}
res.send(result.rows);
client.end();
});
});
app.get is the controller which catches this request and handles it because it's
app.get('/consulting') which matches the destination of the request.
Now this controller has a bunch of codes, it basically sends a request to the Postgres database saying "SELECT * FROM questionaire" which basically means give me all the entries inside the questionaire table.
the database responds with that, so the server (the controller) takes care of the response from the database and forwards it back to the website.
Hope this helps.

NodeJS getting response from net socket write

I'm trying to get a response from specific requests via the write function.
I'm connected to an equipment via the net module (which is the only way to communicate with it). Currently, I have an .on('data',function) to listen to responses from the said equipment. I can send commands via the write functions to which I am expecting to receive a line of response. How can I go about doing this?
Current code:
server = net.Socket();
// connect to server
server.connect(<port>,<ip>,()=>{
console.log("Connected to server!");
});
// log data coming from the server
server.on("data",(data)=>{
console.log(''+data);
});
// send command to server
exports.write = function(command){
server.write(command+"\r\n");
};
This is a working code. Sending a command to the equipment via server.write returns a response which right now only appears in Terminal. I'd like to return that response right after the write request. Preferably within the exports.write function.
Add a callback argument to your exports.write function can solve your problem.
exports.write = function(command, callback){
server.write(command+"\r\n");
server.on('data', function (data) {
//this data is a Buffer object
callback(null, data)
});
server.on('error', function (error) {
callback(error, null)
});
};
call your write function
var server = require('./serverFilePath')
server.write('callback works', function(error, data){
console.log('Received: ' + data)
})

Handling ajax requests, not receiving data

i'm having a hard time setting up my client-side ajax calls to send data to node express server.
i want to fire my ajax request "onclick" of an href link.
I'm trying to send the ID of the link as a variable to the server, but the server doesn't receive my data (without setInterval)
if i put the ajax request inside a setInterval() (which i don't want to do, because i only want to send the data once a link is clicked to the server),
the server receives the data in res.req.body, why?
client side:
$('.link_group').click(function () {
data = $(this).attr('id');
$.ajax({
type: "POST",
url: "/ajax_handler",
data: {id: data}
});
});
server side
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(res.req.body) {
console.log(res.req.body);
}
});
Is this even a common way to "catch" the data from client?
if(res.req.body) {...
doesn't seems right, but i don't know how to do it in a smarter way / can't find any good examples.
I'm about to fire 3-4 Ajax other requests to /ajax_handler which leads to my next question: how to handle multiple ajax requests to the same url?
Thanks in advance!
Are you parsing the request? req.body is initially empty/undefined. You will need to pass it to a middleware that parses the data into req.body. Body-parser is a nodejs module that can achieve this. Here's how to a POST request with JSON data being sent.
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(req.body) {
console.log(req.body);
}
});

Neither Node.js PUT or POST routes are presenting the data that is being received

I tried this with a number of different modules and methods.
Even by proving the other modules do work as expected in Node by building a separate test project and testing each module individually.
Posting FROM Node's hosted router to a remote API (not TO Node's hosted API)
This problem is not one of SENDING data to an API. It must IMO a problem in the receiving API's not giving up the data it IS receiving for some reason.
I've proven the PUT or POST calls are sending the data by sending the call to http://httpbin/org. That site shows me I'm sending what I expect to be sending.
Here is how I'm sending. I can even see in the receiving API that that API is certainly getting called successfully.
-- sending -- ((Again. This shows my node.http attempt. But I get the same problem using requestjs, requestifyjs, needlejs))
router.get('/', function (req, res, next) {
var hst = req.headers.host.split(':');
var lookbackURL = 'https://' + req.headers.host + req.baseUrl;
lookbackURL = 'http"httpbin.org/put';
var dat = {
what: 'ever'
, try: 'again'
};
var bdy = JSON.stringify(dat);
var options = {
host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT'
, headers: { 'Content-Type': 'application/json' }
};
var r = nodeHttp.request(options); r.write(bdy); r.end();
res.sendStatus(200);
});
-- receiving --
router.put('/', function (req, res, next) {
console.log('r', req);
});
No matter what module or method I use, in all cases, the receiving req object doesn't contain the what or try data.
BUT in my test project the data is there as I expect it to be, in all cases.
Doing the same console.log(req); in the test project, reqestjs, requestjs, needlejs, node.http all show a proper body object.
But in this problem there isn't a body object in req.
And sending this put/post to http://httpbin.org I can see the body object is being sent.
Any ideas?
Issue found. And it was something no one on here could have gotten for the code I posted.
For reasons I will not go into I have to take body-parser out this application. This also means app.use() won't have a parser given to it.
And that means I have to deal with getting the data on my own. So I've added a req.on('data') listener to read the chunk from the call to the API.
router.put('/', function (req, res, next) {
var data = '';
req.on('data', function (chunk) {
data += chunk;
.....
});
.....
I also decided to do this as a PUT using Requestify.
This just goes to show how easy it is to become complacent and forget how things really work; the assumption of body-parser (or other things) always being there for instance. Or what it is really doing for you.
NEXT I have to figure out how to get a value out of the `req.on('data) back to the method PUTting to the API. Any tips? Appreciated.

Node JS HTTP GET request body

I am using the express module in node.js and I am trying to read the body of an HTTP GET request and send an answer back to the user based on the content of the body. I am new to node.js and this is not working for me.
I know I should be using HTTP POST for this (and it works when I am using post), but the server I am trying to mimic in node.js uses GET, so I have to stick to it. Is there a way to do this in node.js? Thanks!
Here is a sample code I did. When I use app.post, I see the logs for the body, but when I use app.get, I see no logs at all!
app.get('/someURL/', function(req, res){
var postData = '';
req.on('data', function(chunk) {
console.log("chunk request:");
console.log(chunk);
postData += chunk;
});
req.on('end', function() {
console.log("body request:");
console.log(postData);
});
//Manipulate response based on postData information
var bodyResponse = "some data based on request body"
res.setHeader('Content-Type', 'application/json;charset=utf-8');
res.setHeader('Content-Length', bodyResponse.length);
res.send(bodyResponse);
};
The version of Node's HTML parser you are using does not support bodies in GET requests. This feature is available on the latest unstable v0.11 branch.
https://github.com/joyent/node/issues/7575
https://github.com/joyent/node/issues/5767

Categories

Resources