Parameter restriction with Node.js - node.js

What I want to do is check the script URL for a parameter & display the content of that parameter like:
www.mywebsite.com/mynodescript.js?parameter=i+am+new+to+node!
Now I want to display "I am new to node!" on browser screen and if the parameter is not present I just want to exit.
edit:
I found this code but I am not sure how to deploy it
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Note: i want to upload my script on heroku & want it to call it remotely

When you say you don't know how to deploy it, I'm assuming you don't have a http server setup yet?
Look at using Express (http://expressjs.com/). It's easy enough to get started with.
Create a file called app.js like this:
const express = require('express')
const app = express()
// This handles the path /mynodescript.js You can create a bunch of functions like this to handle different paths. See the express docs for more.
app.get('/mynodescript.js', (req, res)=>{
let parameter = req.query.parameter; // <-- Could also do let {parameter} = req.query This is where you would pull out your url parameters
if(parameter){
res.send(parameter); // <-- this sends it back to the browser.
}else{
res.status(422).end(); // <-- you can set a status here or send an error message or something useful.
}
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Start the script using node app.js from the same directory.
Then open a browser and go to http://localhost:3000/mynodescript.js?parameter=i+am+new+to+node and you should see your parameter
Note that you will have to install express first npm install express --save
Note that you do not have to use express. There are quite a few http libraries available for nodejs. Or you can use the built-in http server (https://nodejs.org/api/http.html). It's good to get familiar with the NodeJS docs, but their http server is cumbersome to work with.

Related

How to interact with a node.js script in the browser?

I'm unfamiliar with node and don't know where to start looking, or what exact question to ask.
I have a server on which I can run javascript through node. So:
node myfile.js
Now, I want to be able to browse to this server, passing a query string variable:
https://myserver.com/somefile.html?somevariable=1
Then, I want to pass the somevariable to the node script myfile.js, get the result back from myfile.js, and present the result in the browser.
How do I do this?
I'd happily call myfile.js directly in the browser, too, but that won't run the script through node nor would it output the result to the browser.
(More specifically, I want to pass the value of somevariable from a PHP page on another server and then process the result on that PHP page.)
So if I understand your question correctly, you want to create an API in NodeJS.
Take a look at: https://github.com/expressjs/express
const express = require('express')
const app = express()
app.get('/someRoute', function (req, res) {
console.log(req.query.somevariable)
res.send(`Some Variable: ${req.query.somevariable}`)
})
app.listen(3000)
https://localhost:3000/someRoute?somevariable=1

How to get url of a page that makes a http ajax GET request in node.js?

In node.js I have a site that serves pages from the same server. Pages can request for files on the same server using http get with ajax. However some pages are not allowed to request a file from a certain path. How can I validate this in node.js?
Also this should be in a way a user can't hack from client side. The node.js would need a way to see if the request came from a page from a certain url and if so then block it if the link it requests is in a specified folder.
Thanks
Assuming you've setup your server like so:
var http = require('http');
server = http.createServer(function(req, res)
{
...
you can get the referring URL by accessing req.headers.referer
Then you'll need to check this either with a regular expression (if the allowed URLs match a pattern) or against an array of acceptable values.
UPDATE
Next, you could keep an array of valid visited URLs in a session and then check if the acceptable referring URL is actually in this list (and thus not necessarily spoofed).
In any node function , we have access to request and response object. Consider the following eg :
var express = require('express');
var router = express.Router();
var app = express();
app.get('/', function(request, response){
var urlPath = request.path;
response.send("Hello");
});
app.listen(3000);

Why combine http module with express module

Hello guys i'm new to node js and started researching and working on some tutorials. I just want a better understanding or clarification on a doubt i had. So i came across the in built module http. This helps in creating a a basic web server. Now express module is a web framework that is built on top the http module that makes it easy using a fully wedged web server without reinventing the wheel. Now I came across this code:
var express = require( 'express' )
, http = require("http")
http.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen(8080);
But in express one could simply just do this
var express = require('express');
var app = express();
app.listen(8080, function() {
console.log('Listening on ' + 8080);});
What's the difference between both? Don't they both accomplish the same thing. If not what's the difference and advantage of using the first approach. Should one adhere to the first approach as it's a good programming practice. That's my doubt as i just want a clear understanding if there's any difference.
Why combine http module with express module
There's really no reason to create your own http server using the http module. Express will just do that for you with app.listen() just fine and save you little bit of typing.
If you were creating an https server, then you would need to use the https module and pass security credentials to https.createServer(...) in order to create a properly configured server. Express does not have the ability to create a properly configured https server for you automatically.
If you look at the Express code in GitHub for app.listen(), it shows this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, there's really no difference (other than a little less typing) when you use app.listen() or create your own http server and then use app as the listener to that server.
So, these two code snippets are identical in function:
var app = require('express')();
app.listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
The above code is functionally identical to:
var http = require('http');
var app = require('express')();
http.createServer(app).listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
Of course, if you're trying to set up https servers or add custom options to the .createServer() method, then you will set up your own server first and then pass app to it as the listener. app.listen(...) is just a shortcut when the default http.createServer() works fine.

Get response of Node.js Express app as a string

How does one get the response of an express app as a string given a request object?
In other words, I want a way to send a request object to an express app and receive its response as a string.
As code, I am looking for some implementation of the sendToThisApp method:
var app = express();
app.get( /* Some code here */ );
var request = // Some request object
var response = app.sendToThisApp(req)
console.log(response);
Thanks.
Here is the code for a simple Node.js Express app :
var app, express;
express = require('express');
app = express();
app.get('/', function(req, res) {
console.log(res);
res.end();
});
app.listen(8080);
In order to trigger a get request on this app, you need to run the app on node. Open a terminal and type this command:
node app.js
Then, you only need to start your favorite browser, go to localhost:8080, and look back at the log of the response in your terminal.
It looks like you're expecting things to happen synchronously that node and express want to handle asynchronously through callbacks.
But aside from that, I'm not really understanding what you're trying to do.
If you have the code for the node app, and you just want to see the response object as a string, then the easiest way to handle that is through the callback on the get.
app.get('/', function(req,res){
console.log(res);
}
But without knowing what you're actually after, I can't give better advice.

Twilio $_REQUEST['From'] equivalent for node.js

I'm trying to use 'twilio' to grab the caller ID from an incoming phone call. I managed to do this easily in my call.php file using the following:
$callerId=($_REQUEST['From']);
I have now redirected my twilio phone number to access a different URL so that I can use it with node.js (ie call.php is now call.js). However, I cannot seem to request the ['From'] field in a similar manner as with the .php file. Is this possible? What is the easiest way to grab a caller Id and store it in a variable using node.js?
Any thoughts appreciated.
For the sake of completeness, here's a full example of getting Twilio request parameters using Express. Before running, make sure to install dependencies with npm install twilio express. You might also benefit from reading this blog post introducing the Twilio node.js module.
This code is an example of responding to an inbound phone call:
// Module dependencies
var twilio = require('twilio'),
express = require('express');
// Create an Express webapp, and use a middleware
// that parses incoming POST parameters
var app = express();
app.use(express.urlencoded());
// Create a route that responds to a phone call by saying
// the caller's number
app.post('/call', function(request, response) {
var twiml = new twilio.TwimlResponse();
twiml.say('Hello, you called from ' + request.param('From'));
response.type('text/xml');
response.send(twiml.toString());
});
// Start the app on port 3000
app.listen(3000);

Resources