Nodejs - What is the use of req.url parameter? - javascript

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(2020);
What is the use of req.url parameter? Will it be alright if I don't use it? Also, does passing a parameter in res.write(); produce the same result as passing a parameter in res.write();

Suppose you are building an web app which loads some data when user clicks to the "fetch posts" button, now what happens browser fires http request and load data from server.However if user opens browsers developer tool and navigates to the "Network" tab and click the "fetch post" button then there will be an entry for the Http call like :- http://domain.tld/fetch-posts .So if user copies your url in the an script an call it in loop for huge number like 10^9,then your server would not be able to serve others and probably crashed or if it is at auto scaling then god may help you to pay cost.This issue can prevented without using captcha with help of req.url in NodeJS,to use this we can make a general route like http://domain.tld/invoke and send encrypted parameters for next route to be called and then replace that parameter with req.url at server like req.url = req.body.path and call next() using ExpressJs.So each time user sees network tab there is one kind of url i.e http://domain.tld/invoke

Related

Express get request with an :id-parameter being run twice

I have an API made with node and express, and the end goal is to store the :id-parameter from the request in a variable so that I can query a specific table from my SQLite database with a specific id. Now the get request with an :id-parameter is being run twice, once with the request url being what it´s supposed to be (in my case "page") and once with the url /serviceWorker.js.
This is the code from my router with the get-request:
import express from "express";
const router = express.Router();
router.get("/:id", function (req, res) {
const id = req.params.id;
console.log("id:", id);
console.log("Req url:", req.url);
res.send(id);
});
export default router
The console log from a single get request looks like this:
id: molekylverkstan
Req url: /molekylverkstan
id: serviceWorker.js
Req url: /serviceWorker.js
Even when running the get request for my home page, with this code:
router.get("/", function (req, res) {
res.render("../pages/start.ejs");
});
I get the console log:
id: serviceWorker.js
Req url: /serviceWorker.js
I tried breaking the request with break(), return, and next() but nothing worked. I have no service worker in my project which makes me wonder why it comes out of nowhere. Maybe I need som kind of service worker, or to specifically state somewhere in my project that it shouldn´t look for one?
Even though you don't have a service worker in your project, there might still be one registered in your browser from a previous project that you ran on the same domain/IP address in the past.
The reason you are getting this request is that your browser no longer has the valid cached version of the service worker and tries to reload it. But since that request fails, it will try over and over again.
To remove it, open the website in question and check your browser developer tools (Application -> Service Workers or chrome and firefox), and unregister any service workers you no longer want to use.

What's the difference between res.redirect and res.sendfile?

I completed a tutorial challenge of setting up a 'failure' page and a 'Try again' button. The button takes the user back to '/signup/html'. I used
app.post("/failure", (req, res) => {
res.sendFile(__dirname + "/signup.html");
});
But the tutorial used the res.redirect method.
The result is the same, but what's happening in the background, are there any differences using
res.redirect and res.sendFile?
Thanks,
On the face of it, redirect issues a redirect but sendFile sends a file.
I'm going to assume that code elsewhere responds to whatever path the tutorial said to use with redirect (let's say /signin) by sending that same file. So it might seem the same, but there are important differences:
Using redirect means you're only specifying that filename in one place, not two, which is better for maintenance.
If there's middleware set up on the other route (/signin or whatever), that middleware will get run with a redirect but not with your code.
redirect sends a message back to the browser telling it to request the other URL; your code sends the file directly.
With redirect, you can specify the redirect HTTP status code to use, for instance if you wanted to tell the client that the redirection is permanent (by specifying status code 302, though in your example that probably wouldn't be appropriate).

How to route a Node.js Single Page App?

I'm trying to design a Single Page App using Node.js that has multiple tabs, and on each tab can contain a number of images or scripts, so I'd like to prevent loading the content of every tab each time a user visits the page. So ideally when a user switches tabs the server would send the html which contains the images and scripts and the client would display that without reloading the page.
The reason I chose the SPA design is that outside the tabs would be a chat system amongst other things running in the background that I don't want to resend to clients each time a redirect happens.
So my question is what is the best way to send the html, or is there a better way in general that still uses the SPA design?
Would the best way be to send the html in the router to the client, then use ajax to prevent a page refresh and add new tab html and remove old tab html after that?
You can use Express.js with only one route.
This route could be called:
var app = require('express')();
app.get('/',function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
}
Note that:
This is a GET route
It just sends the file contents with sendFile
After that you can have many API routes to fetch the data for your tabs. I would recommend these routes to be like this:
app.post('/about',function(req, res) {
res.json({ data: "your data here" });
}
app.post('/contact',function(req, res) {
res.json({ data: "your data here" });
}
On these routes note that:
These are POST routes
Only a JSON is returned
SPA means "single page app", and you will only have a single HTML shell that a JavaScript framework will then handle the "pages" and HTML after that

Cannot fetch Signed_request from facebook in request, Pass params to Page Tab

I'm using an express backend and have an app which will need to be customized the url of the page tab with unique id's for every fan page on facebook. (Using app_data)
Problem is I cannot seem to get the signed_request parameter, in the POST request made by FB.
I've even tried using a library : https://www.npmjs.com/package/fb-signed-parser but the param can't be found and it fails.
app.post('*', function(req, res){
console.log(req);
//var signed_request = req.param('signed_request');
....
Can someone point me to the right direction?

Sending message between two users via node.js and socket.io

I'm new with node.js and socket.io
I have two clients, and they have their ID 1 & 2.
I need to send data via socket.io that contain:
user_from, user_to, action
And the data is send from both sides.
How do i send this data from client 1 with socket.emit(), so I can set variable:data ?
How to read that data on server with socket.get ?
And send it again from server to client 2 ?
(i found this code: io.sockets.volatile.emit( 'broadcast_msg' , msg ); but i want to send it only from specific user to specific user, not all users connected.)
Thank you for your help, I see a lot of examples, but not what I need.
UPDATE:
I don't understand this code:
// on server started we can load our client.html page
function handler(req, res) {
fs.readFile(__dirname + '/client.html', function(err, data) {
if(err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
}
Why do I need to do this? I have ex: index.php?menu=30 or index.php?menu=30&action=12
You are looking for routing functionality. What socket.io provides is point-to-point communication. e.g. from 1 client to the server.
So logically, you need the server to route messages, which means that messages should have addressing information (e.g. ID of the target recipient). This can then be used to route messages by, for example, creating (custom) user-specific events to be triggered based on the target user of the incoming message.
If you are building anything that needs to scale, perhaps you should look at a messaging framework like RabbitMQ. It is exactly meant to route messages between distributed entities (like the users).
Cheers!

Categories

Resources