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

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.

Related

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

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

Server Side Routing vs. Front End Routing with Proxy

I hope my question doesn't come off as silly. I have quite a bit of experience on the front end but very little on the back end.
I have a React application which uses Node.js and Express on the back-end. I have declared "proxy": "http://localhost:3001" in my package.json which I am not 100% what this does but I know it is helping to connect my server (which runs on port 3001).
The issue I am having came about while setting up Auth0 on my backend to verify users. The first thing I noticed was that I was not able to run a get request to http://localhost:3001/login instead I had to navigate the user to the url http://localhost:3001/login. I'm not sure why this is but I assume it has something to do with Auth0 settings.
After I login Auth0 returns users to a callback url. Auth0's docs recommend using localhost:3000/callback since there docs also have a backend endpoint at /callback. However after logging in the user just gets routed to an empty page at http://localhost:3000/callback and the backend endpoint is never hit. I found that strange since I was basically copying and pasting from the Auth0 guide to setting up a login with Express.
Anyway I found that if I changed the callback url to my server at http://localhost:3001/callback than the server side code runs. This makes sense other than the Auth0 docs saying to use port 3000. It seems like maybe my proxy should be linking these somehow.
The callback endpoint function looks like this:
router.get('/callback', function (req, res, next) {
console.log('called')
passport.authenticate('auth0', function (err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/login');
}
req.logIn(user, function (err) {
if (err) {
return next(err);
}
const returnTo = req.session.returnTo;
delete req.session.returnTo;
res.redirect(returnTo || '/user');
});
})(req, res, next);
});
When this runs successfully it should route the user to my Users page at localhost:3000/users however because I changed the callback route to 'localhost:3001/callbackthe callback endpoint is routing me tolocalhost:3001/users`.
I can kind of see what is going on. When I go to a url using 3001 I am hitting my endpoints. When I go to a url using 3000 I am viewing my front end pages. I just don't understand why the Auth0 docs would tell me to use my front end port for the callback?
I'll try to help but I'm not sure this is the answer.
If you set in your package.json the proxy to "proxy": "http://localhost:3001" then in your app to make a request you don't need to use the full URL,
axios.get('/login').then(res=>res.data).catch(err=>console.log(err));
For example without the proxy setted
axios.get('http://localhost:3001/login').then(res=>res.data).catch(err=>console.log(err));
In Auth0 the host URL and port is not a problem, U can use whatever U want, the point is the /callback route, in Auth0 you can configure a custom route for the callback but by default in your app, you need to have a route /callback. remember to add localhost:3001 to Auth0 configurations
I hope to help.

VueJS Secure with Auth0 - How is it secure?

I'm missing some sort of (most likely simple) fundamental understanding of securing a JavaScript application such as one using the VueJS framework and a service like Auth0 (or any other OAuth server/service).
1) If you create a SPA VueJS app with routes that require authentication, what stops a user from viewing your bundled code and seeing the views/templates behind that route without needing to login?
2) If you create a VueJS app that authenticates a user and sets some variable in a component like isLoggedIn = true or isAdminUser = true, what stops the user from manipulating the DOM and forcing these values to true?
All your JavaScript code is exposed to the client, so how is any of your code/content actually secure if it can be explored on the code level?
1) You understand correctly, nothing stops him. That's why you always do all that on the server side. The code in browser/VueJS is only to make the interface make sense, like hiding a button, but the server code should always do the actual check.
For example:
You have a button "Get secret document" that has a axios request behind to the path /api/sendsecret
In your VueJS app you can do something like v-if="user.isAdmin" to only show the button to the user.
There's nothing from stopping a user to find that path and just hit it manually with curl or postmaster or any other similar tool
Thats why the server code (nodeJS with express for example) should always do the checking:
app.get('api/sendsecret', (req, res) => {
if (req.user.isAdmin) {
res.send('the big secret')
} else {
res.sendStatus(401) // Unauthorized
}
})
2) Again, nothing. You should never authenticate a user in the VueJS application. Its ok to have some variables like isLoggedIn or isAdminUser to make the interface make sense but the server code should always to the actual authentication or authorization.
Another example. Lets say you're gonna save a blog post
axios.post('/api/save', {
title: 'My Blog Post'
userId: 'bergur'
}
The server should never, never read that userId and use that blindly. It should use the actual user on the request.
app.post('api/save', (req, res) => {
if (req.user.userId === 'bergur') {
database.saveBlogpost(req.body)
} else {
res.sendStatus(401)
}
})
Regarding your final marks:
All your JavaScript code is exposed to the client, so how is any of
your code/content actually secure if it can be explored on the code
level?
You are correct, its not secure. The client should have variables that help the UI make sense, but the server should never trust it and always check the actually user on the request. The client code should also never contain a password or a token (for example saving JSONWebToken in local storage).
Its always the server's job to check if the request is valid. You can see an example on the Auth0 website for NodeJS with Express.
https://auth0.com/docs/quickstart/backend/nodejs/01-authorization
// server.js
// This route doesn't need authentication
app.get('/api/public', function(req, res) {
res.json({
message: 'Hello from a public endpoint! You don\'t need to be authenticated to see this.'
});
});
// This route need authentication
app.get('/api/private', checkJwt, function(req, res) {
res.json({
message: 'Hello from a private endpoint! You need to be authenticated to see this.'
});
});
Notice the checkJwt on the private route. This is an express middleware that checks if the user access token on the request is valid.

Running a node.js file from website

I have recently started using the Twilio platform to send SMS to my users. I am perfectly able to run the node.js file from the node terminal with the command:
node twilio.js
Now, my goal is to be able to send those SMS, but from my website. For instance, when the user provides his phone number and presses the "Send sms" button. How can I achieve this? I have been looking this up for a while and I came across Express platform, ajax post requests, http server, etc. But, I can't figure out how to use them. I currently make many ajax requests (POST and GET) on my site, but I'm not able to make a request to a node file.
Thanks in advance,
Here is the twilio.js file:
// Twilio Credentials
var accountSid = 'ACCOUNT SID';
var authToken = 'ACCOUNT TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
client.messages.create({
to: 'TO',
from: 'FROM',
body: 'Message sent from Twilio!',
}, function (err, message) {
console.log(message.sid);
});
Being able to run any arbitrary script on your server from a webpage would be a huge security risk - don't do that. I'm not sure where you're hosting your site, or what technology stack you're running your site on, but since you mentioned Express and Node -- if you're using Express I'd recommend that you setup a route that handles an ajax request. When someone presses 'Send SMS' you send an ajax request to that route, and in the handler that gets invoked you place the Twilio logic.
Here is a very simple way to setup an Express request that calls you node module:
twilio.js:
// Twilio Credentials
var accountSid = 'ACCOUNT SID';
var authToken = 'ACCOUNT TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
function sendSms(callback) {
client.messages.create({
to: 'TO',
from: 'FROM',
body: 'Message sent from Twilio!',
}, callback);
}
// Export this function as a node module so that you can require it elsewhere
module.exports = sendSms;
Here is a good start for Express.
server.js:
var express = require('express');
var app = express();
// Requiring that function that you exported
var twilio = require('/path/to/twilio.js');
// Creating a controller for the get request: localhost:8081/send/sms
app.get('/send/sms', function (req, res) {
twilio(function(err, message) {
if (err) res.send(err);
res.send('Message sent: ' + message);
});
});
// Creating an HTTP server that listens on port 8081 (localhost:8081)
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
Then you can run node server.js, go to your browser and go to the url: localhost:8081/send/sms and your message will be sent :)
I'd make it so the client sends a HTTP POST request to the server, and then the server will send the message on behalf of the client.
Easiest way is to use express. I'm a bit unsure of how you're serving your website from a Node.js app without using express. Do you have a custom solution or only a non-connected from end, or something like heroku or something? In any case, you can create a route that processes posts with the following:
app.post("send_twilio_message_route", function(req,res){
// this receives the post request -- process here
});
^ Note that doesn't actually create the express app. See my link below and they give examples of some of the nitty gritty and syntax.
So the above would be on the server, in your Node.js app. From the front-end client code that runs in the browser, you need to create a post. The easiest way and most likely way to do it is through $.post in Jquery. if you are using Angular there's a slightly different syntax but it's the same idea. You call post, point it to a url, and put in the body data.
Make the body of the post request contain data such the message, phone numbers,
authentication token maybe.
See this to be able to get the body from a post request and some more implementation details of how to set it up:
How to retrieve POST query parameters?
Depending on the nature of what you're doing you might consider having the sms processing stuff run separate from the actual web service. I would create the sms unique stuff as its own module and have a function retrieve the router so that you can mount is onto the app and move it about later. This might be overkill if you're doing something small, but I'm basically encouraging you to at the start put thought into isolating your services of your website, else you will create a mess. That being said, if it's just a small thing and just for you it might not matter. Depends on your needs.
Important: I highly encourage you to think about the malicious user aka me. If you don't add any authentication in the post body (or you could include it in the url but I wouldn't do that although it's equivalent), a malicious client could totally be a jerk and expend all of your twilio resources. So once you get it basic up in running, before deploying it to anything that people will see it, I recommend you add authentication and rate limiting.

Node.js: Changes on route settings don't show effect

For some strange reason, some changes on my route settings (MEAN environment, Node v0.12.2 and express 4) don't show effect any more!? Particularly instructions where I respond to client requests using ".sendfile()".
app.get('/', function(req, res){
res.sendfile("/public/index.html"); // <-- trying to exclude or change this
console.log("debug message"); //added later, never shown!!
});
Excluding or altering the sendfile instruction in the example above doesn't change anything - index.html is alyways being delivered upon request. Not even simple debug messages like console.log are shown any more?! Here's what I checked:
restarted Node.js server and computer several times
checked for duplicates of routes.js file
checked for duplicates of home route ("/")
cleaned browser cache
even deleted the ENTIRE route, site still delivered upon request!?!?
Maybe there is some kind of server-side cache that needs to be wiped?! I got no idea any more of what's wrong. Suggestions anyone?
There are changes in express 4 with respect to express 3. In express 4 we have got a new method app.route() to create chainable route handlers for a route path and a new class express.Router to create modular mountable route handlers. For more details ref: Moving to Express 4 What you can do is try using code in following order:
app.route('/')
.get(function(req, res) {
res.render('index');
});
And its also good serve static files by adding:
app.use(express.static(path.join(__dirname, '../public')));
Good luck...:)

Categories

Resources