One place for hosting & domains

      ExpressJS

      Use ExpressJS to Deliver HTML Files


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      In Node.js and ExpressJS applications, there used to be a very simple way to deliver an HTML file or any other sort of file: res.sendfile(). Delivering HTML files using Express helps make development quick and easy when you need a quick HTTP server.

      Recently, this function has become deprecated by ExpressJS and if you try using the function, you’ll get an error saying that function is deprecated and you should use res.sendFile().

      Using res.sendFile()

      To use res.sendFile, we will need to pass in a path to the file.

      We will also need to pull in the built-in path module so that we can link to the file.

      Here is an example of using res.sendFile() to deliver an HTML page.

      var express = require('express');
      var app = express();
      var path = require('path');
      
      // viewed at http://localhost:8080
      app.get('/', function(req, res) {
          res.sendFile(path.join(__dirname + '/index.html'));
      });
      
      app.listen(8080);
      

      Sample Code

      We’ll need a Node application to start. So you can create one by running the following commands:

      • mkdir express-sendfile
      • cd sendfile
      • npm init
      • npm install express --save
      • touch server.js index.html

      Now we have the foundation for our quick Node app. server.js will be the file that will contain the route to serve our index.html file.

      server.js

      var express = require('express');
      var app = express();
      var path = require('path');
      
      // viewed at http://localhost:8080
      app.get('/', function(req, res) {
          res.sendFile(path.join(__dirname + '/index.html'));
      });
      
      app.listen(8080);
      

      index.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Sample Site</title>
      
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
          <style>
              body { padding-top:50px; }
          </style>
      </head>
      <body>
      
          <div class="container">
              <div class="jumbotron">
                  <h1>res.sendFile() Works!</h1>
              </div>
          </div>
      
      </body>
      </html>
      

      Now after our server has been started using:

      We can see our site in our browser!

      example html file served through expressjs

      Conclusion

      res.sendFile() is a very easy function to use. Express provides a great many tools for Node users and we can even use this to deliver downloadable files or any files really.



      Source link

      Use ExpressJS to Get URL and POST Parameters


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      Often when we are building applications using ExpressJS, we will need to get information from our users.

      This can happen any number of ways but the two most popular are:

      URL Parameters

      These are information that are passed through the URL like so:

      http://example.com/api/users?id=4&token=sdfa3&geo=us
      

      This is most seen in requesting information from an API.

      URL Parameters are grabbed using req.param.variable_name

      POST Parameters

      These are information that come from forms. We’ll be grabbing from forms that pass information as application/x-www-form-urlencoded.

      POST Parameters are grabbed using req.body.variable_name

      Let’s take a look at how we can grab the parameters using the popular Node.js framework, ExpressJS.

      Sample App to Test

      We’ll be creating a sample application to make sure that grabbing parameters works. We’ll also be using POSTman to test the form POST.

      We’ll only need two files:

      - package.json
      - server.js
      

      Here is the package.json

      {
          "name": "express-parameters",
          "main": "server.js",
          "dependencies": {
          "express": "~4.10.2"
          }
      }
      

      Here’s the start of our server.js:

      // grab the packages we need
      var express = require('express');
      var app = express();
      var port = process.env.PORT || 8080;
      
      // routes will go here
      
      // start the server
      app.listen(port);
      console.log('Server started! At http://localhost:' + port);
      

      We can now start our server using:

      You will have to restart the node server every time you edit server.js. If this gets tedious, see how To Restart Your Node.js Apps Automatically with nodemon.

      Now let’s create two routes now to test grabbing parameters.

      Getting Any URL Parameter

      For this example, we’ll grab a parameter directly from the URL. Let’s say we are using the example URL: http://example.com/api/users?id=4&token=sdfa3&geo=us

      The parameters that come out of this will be:

      id: 4
      token: sdfa3
      geo: us
      

      It’s very easy to grab these parameters. Here’s the route and the method for grabbing parameters is req.param().

      // routes will go here
      app.get('/api/users', function(req, res) {
          var user_id = req.param('id');
          var token = req.param('token');
          var geo = req.param('geo');  
      
          res.send(user_id + ' ' + token + ' ' + geo);
      });
      

      The parameters are naturally passed through the req (request) part. Now if we go to our browser at http://localhost:8080/api/users?id=4&token=sdfa3&geo=us, we’ll be able to see the three parameters!

      Specific Routing for Specific Parameters

      We can also name the paramter directly in the route itself. Here’s a URL and example:

      // http://localhost:8080/api/1
      app.get('/api/:version', function(req, res) {
          res.send(req.params.version);
      });
      

      Route Parameter Middleware

      Next up, we’ll be using the Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

      This can be used for validations (like checking if a user exists) or grabbing important information about that user or item.

      An example for this would be:

      // parameter middleware that will run before the next routes
      app.param('name', function(req, res, next, name) {
      
          // check if the user with that name exists
          // do some validations
          // add -dude to the name
          var modified = name + '-dude';
      
          // save name to the request
          req.name = modified;
      
          next();
      });
      
      // http://localhost:8080/api/users/chris
      app.get('/api/users/:name', function(req, res) {
          // the user was found and is available in req.user
          res.send('What is up ' + req.name + '!');
      });
      

      If we visit the URL in our browser, we’ll see:

      What is up chris-dude!

      Pretty neat. You can use this param middleware for validations and making sure that information passed through is valid and the correct format.

      We then save information to the request (req) so that our other route will have access to it.

      Further Reading More Express routing: Learn to Use the Express 4.0 Router

      POST Parameters

      To get POST parameters, we’ll need two the ExpressJS body-parser package. This will allow us to grab information from the POST.

      Install body-parser

      We’ll need to install body-parser using:

      • npm install body-parser --save

      Now that we have that package and it has been added to our package.json thanks to the --save modifier, we have to configure it in our server.js file.

      Add the following after you define the app variable.

      var bodyParser = require('body-parser');
      app.use(bodyParser.json()); // support json encoded bodies
      app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
      

      With body-parser configured, we can now create our route:

      We will grab POST parameters using req.body.variable_name

      // POST http://localhost:8080/api/users
      // parameters sent with 
      app.post('/api/users', function(req, res) {
          var user_id = req.body.id;
          var token = req.body.token;
          var geo = req.body.geo;
      
          res.send(user_id + ' ' + token + ' ' + geo);
      });
      

      We can test this using POSTman and send information as application/x-www-form-urlencoded:

      Conclusion

      Those are the quick ways we can grab information using ExpressJS. Grabbing data from the request is an easy enough process.

      Just grab the information quick and easily so that you can move on to building great things!



      Source link