Categories
Express JavaScript Nodejs

Processing File Upload with the Express Multer Middleware

Multer is a middleware that lets us process file uploads with our Express app.

In this article, we’ll look at how to use it to process uploads and process text data in multipart forms.

How to Use it?

We can install it by running:

npm install --save multer

Once it’s installed we have to make a form that has the encoding type multipart/form-data .

It won’t process any form that’s not multipart, i.e. has the enctype set to multipart/form-data .

Simple Usage

The simplest usage is to allow upload of one file at a time. We can do this by calling the multer function and setting the path to store the uploaded file as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const multer = require('multer');  
const upload = multer({ dest: './uploads/' });  
const app = express();
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {  
  res.sendFile('public/index.html');  
});
app.post('/upload', upload.single('upload'), (req, res) => {  
  res.send('file uploaded')  
});
app.listen(3000, () => console.log('server started'));

Then we can create index.html in the public folder and add:

<!DOCTYPE html>  
<html>
<head>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width">  
  <title>Upload</title>  
  <link href="style.css" rel="stylesheet" type="text/css" />  
</head>
<body>  
  <form action="/upload" method="post" enctype="multipart/form-data">  
    <input type="file" name="upload" />      
    <input type='submit' value='Upload'>  
  </form>  
</body>
</html>

The code for index.html will make the form submit multipart form data.

Also, the value of thename attribute has to match with the name string that’s passed into the upload.single() method.

Once the file is upload, a random ID will be generated for the uploaded file’s name.

req.files will have the file objects and req.body will have the values of the text fields.

Uploading Multiple Files

We can also process the upload of multiple files with the upload.array method as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const multer = require('multer');  
const upload = multer({ dest: './uploads/' });  
const app = express();
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {  
  res.sendFile('public/index.html');  
});
app.post('/upload', upload.array('uploads', 5), (req, res) => {  
  res.send('files uploaded')  
});
app.listen(3000, () => console.log('server started'));

Then we have to change index.html to:

<!DOCTYPE html>  
<html>
<head>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width">  
  <title>Upload</title>  
  <link href="style.css" rel="stylesheet" type="text/css" />  
</head>
<body>  
  <form action="/upload" method="post" enctype="multipart/form-data">  
    <input type="file" name="uploads" multiple />  
    <input type='submit' value='Upload'>  
  </form>  
</body>
</html>

We add the multiple attribute to the form to enable multiple uploads in addition to using the upload.array method.

The 5 in the second argument of the upload.array call is the maximum number of files that we can upload.

Once the file is upload, a random ID will be generated for the uploaded file’s name.

Multiple File Fields

We can enable upload of multiple files as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const multer = require('multer');  
const upload = multer({ dest: './uploads/' });  
const app = express();
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {  
  res.sendFile('public/index.html');  
});
const multiUpload = upload.fields([  
  { name: 'photos', maxCount: 3 },  
  { name: 'texts', maxCount: 5 }  
])  
app.post('/upload', multiUpload, (req, res) => {  
  console.log(req.files);  
  res.send('files uploaded');  
});
app.listen(3000, () => console.log('server started'));

Then when we have the following in public/index.html :

<!DOCTYPE html>  
<html><head>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width">  
  <title>Upload</title>  
  <link href="style.css" rel="stylesheet" type="text/css" />  
</head><body>  
  <form action="/upload" method="post" enctype="multipart/form-data">  
    <label>Photos</label>  
    <br>  
    <input type="file" name="photos" multiple />  
    <br>  
    <label>Texts</label>  
    <br>  
    <input type="file" name="texts" multiple />  
    <br>  
    <input type='submit' value='Upload'>  
  </form>  
</body></html>

We get the files uploaded after we select the files and submit them. The code:

const multiUpload = upload.fields([  
  { name: 'photos', maxCount: 3 },  
  { name: 'texts', maxCount: 5 }  
])

Gets the files from the fields photos and texts and upload to 3 and 5 files respectively.

In the console.log , we see the files of the POST /upload route that we uploaded.

Upload Nothing

To skip the processing of upload files, we can use the upload.none() method as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const multer = require('multer');  
const upload = multer();  
const app = express();
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {  
  res.sendFile('public/index.html');  
});
app.post('/submit', upload.none(), (req, res) => {  
  res.send(req.body)  
});
app.listen(3000, () => console.log('server started'));

Then when have the following for public/index.html :

<!DOCTYPE html>  
<html><head>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width">  
  <title>Upload</title>  
  <link href="style.css" rel="stylesheet" type="text/css" />  
</head><body>  
  <form action="/submit" method="post" enctype="multipart/form-data">  
    <input type="text" name="name" />      
    <input type='submit' value='Submit'>  
  </form>  
</body></html>

We get the submitted POST body in req.body as we can see from the response after typing in something and clicking Submit.

Conclusion

Multer is very useful for processing any kind of multipart forms. It can process uploads of a single file or multiple files. It can also process uploads for multiple fields.

The files uploaded are renamed to an automatically generated by default and are stored in the folder that we specified when we called the multer function to create the middleware.

Also, it can ignore uploaded files and just parse the text request body.

Categories
JavaScript Vue

Create a Vue.js Stopwatch

We can create a stopwatch using Vue.js by using built in functions. In this article, we’ll find out how to make a simple stopwatch.

To start, we create new project with the Vue CLI by running npx @vue/cli.

We then select the default options to create a new Vue project.

Next, we can write the following code:

<template>
  <div id="app">
    <button @click="start">Start</button>
    <button @click="stop">Stop</button>
    <button @click="reset">Reset</button>
    <p>{{formattedElapsedTime}}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      elapsedTime: 0,
      timer: undefined
    };
  },
  computed: {
    formattedElapsedTime() {
      const date = new Date(null);
      date.setSeconds(this.elapsedTime / 1000);
      const utc = date.toUTCString();
      return utc.substr(utc.indexOf(":") - 2, 8);
    }
  },
  methods: {
    start() {
      this.timer = setInterval(() => {
        this.elapsedTime += 1000;
      }, 1000);
    },
    stop() {
      clearInterval(this.timer);
    },
    reset() {
      this.elapsedTime = 0;
    }
  }
};
</script>

In the code above, we have the Start, Stop, and Reset buttons. Then we click thev Start, the start method is run, which creates the timer with setInterval and the this.elapsedTime state is updated.

The elapsedTime is converted to a formatted time string with minutes and seconds with the formattedElapsedTime computed property,

The Stop button runs the stop method when it’s clicked, which calls clearInterval to clear the timer.

The reset method is called by the Reset button and resets this.elapsedTime to 0.

Then we’ll see the stopwatch run when we click Start and the timer stops when we click Stop.

The stopwatch goes back to 0 after we click Reset.

Conclusion

We can create a Vue.js stopwatch without adding extra libraries. We just have to use setInterval and clearInterval to start and stop the stopwatch respectively.

Categories
Express JavaScript

Guide to the Express Application Object

The core part of an Express app is the Application object. It’s the application itself.

In this piece, we’ll look at the methods of the app object and what we can do with it.


app.METHOD(path, callback [, callback …])

This method routes an HTTP request. METHOD is a placeholder for various routing methods that Express supports.

It takes the following arguments:

  • path — It can be a string or regex representing paths or patterns of paths. The default is /.
  • callback — a function to handle requests. It can be a middleware function, a series of them, array of them, or a combination of all of the above.

The following routing methods are supported by Express:

  • checkout
  • copy
  • delete
  • get
  • head
  • lock
  • merge
  • mkactivity
  • mkcol
  • move
  • m-search
  • notify
  • options
  • patch
  • post
  • purge
  • put
  • report
  • search
  • subscribe
  • trace
  • unlock
  • unsubscribe

All methods take the same arguments and work exactly the same way. So app.get and app.unlock are the same.


app.param([name], callback)

app.param adds callback triggers for route parameters. name is the parameter or an array of them. callback is a callback function.

The parameters of the callback are the request object, response object, next middleware function, the value of the parameter, and the name of the parameter in the given order.

For example, we can use it as follows:

The code above will get the id URL parameter when it exists with the app.param callback.

Then in the callback, we get id to req.id and call next to call our route handler in app.get.

Then we call res.send(req.id); to send the response with req.id, which we set earlier.

Note that id in app.param has to match :id with the route handlers.

We can pass in an array of parameters that we want to watch for:

Then if we make a request for /1/foo, we’ll get 1 and foo one at a time as the value of the value parameter.


app.path()

app.path returns the path of mounted apps as a string.

For example, we can use it as follows:

Then we get '' for app.path(), '/foo' for foo.path(), and '/foo/bar' for bar.path() since we mounted foo to app and bar to foo.


app.post(path, callback [, callback …])

We can use the app.post method to handle POST requests with the given path by passing in a callback route handler.

It takes the following arguments:

  • path — It can be a string or regex representing paths or patterns of paths. The default is /.
  • callback — a function to handle requests. It can be a middleware function, a series of them, array of them, or a combination of all of the above.

For example, we can use it as follows:

Then when we make a POST request with a client like Postman, we should see “POST request made.”


app.put(path, callback [, callback …])

We can use the app.put method to handle PUT requests with the given path by passing in a callback route handler.

It takes the following arguments:

  • path — It can be a string or regex representing paths or patterns of paths. The default is /.
  • callback — a function to handle requests. It can be a middleware function, a series of them, array of them, or a combination of all of the above.

For example, we can use it as follows:

Then when we make a PUT request with a client like Postman, we should see “PUT request made.”


Conclusion

We can intercept the parameters sent from requests with the app.params method.

To listen to POST requests, we can use the app.post method. To listen to PUT requests, we can use the app.put method.

app.path lets us get the path of mounted apps.

app also has a long list of methods for listening to all kinds of requests.

Categories
JavaScript Vue

Getting Started with Vue.js

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at how to add the Vue.js framework to our app and build our first app.

Script Tag

We can include the Vue.js framework with a script tag.

To do this we can write:

<script src='https://vuejs.org/js/vue.js'></script>

before our app code loads. The URL above has the development version, which has all the warnings but it’s not minified.

To include the production version, we can write:

<script src='https://vuejs.org/js/vue.min.js'></script>

To fix the version to 2.6.11, we can write:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>

We can also import the module in our browser if we don’t need to support Internet Explorer as follows:

<script type="module">     
  import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.esm.browser.js' 
</script>

The vue.esm.browser.js file is already optimized for browsers so it can be used without creating too many requests.

Example

To create our first app, we can create the index.html file as follows:

<!DOCTYPE html>  
<html>  
  <head>  
    <title>Parcel Sandbox</title>  
    <meta charset="UTF-8" />  
    <script src="https://vuejs.org/js/vue.js"></script>  
  </head> <body>  
    <div id="app"></div>  
    <script src="./src/index.js"></script>  
  </body>  
</html>

Then in src/index.js , we can add:

new Vue({  
  template: "<div>{{ 'hello' }}</div>",  
  el: "#app"  
});

Then we should see hello on the screen, since we have a div with the ID app , which is used by Vue.js to render our Vue instance.

The Vue.js compiler is responsible for converting the template into HTML.

In the template above, 'hello' is a JavaScript string, which was converted to HTML text when the Vue compiler runs.

We specified that the template has a div with the text 'hello' in it.

Different Builds of the Vue.js Framework

There are several different builds of the Vue.js framework. They’re:

  • Full — Builds that have the compiler and the runtime. That’s the one we used in the example above.
  • Compiler — Code that’s responsible for compiling template strings into JavaScript render functions
  • Runtime — Code that’s responsible for creating Vue instances, rendering and updating virtual DOM, etc.
  • UMD — A module that can be directly included with a script tag. It includes the runtime and the compiler
  • CommonJS — A module that can be used with older bundlers like Browserify or Webpack 1.
  • ES Module — New to version 2.6. It can be used directly by browsers via <script type='module'> or be used with bundlers like Webpack 2 or Rollup.

Runtime and Compiler

The runtime is used for creating the Vue instance via new Vue .

The compiler is for compiling templates specified by the template option.

This means that:

new Vue({  
  template: "<div>{{ 'hello' }}</div>",  
  el: "#app"  
});

needs the compiler and:

new Vue({  
  el: "#app",  
  render(h) {  
    return h("div", "hello");  
  }  
});

doesn’t.

Template syntax will be much more convenient when our apps get more complex.

When we’re using vue-loader or vueify , templates inside .vue files are precompiled into JavaScript, so we don’t need the compiler in the final bundle.

When we don’t need to use the compiler, then we should use the runtime only build since it’s 30% smaller.

We can include different builds depending on the bundler that we’re using. For example, in Parcel, we can write:

"alias": {       
  "vue" : "./node_modules/vue/dist/vue.common.js"     
}

in package.json .

Vue CLI

We can Vue-CLI automatically create our app and build it so we don’t have to worry about which bundles to choose.

To install it, we can run:

npm install -g @vue/cli

or:

yarn global add @vue/cli

We can then create a project with it by running:

vue create project

or run:

vue ui

to show the GUI to let us create a Vue project in our browser.

Also, we can run the Vue CLI directly with npx by running:

npx vue create project

Running vue create will present us with a wizard with various options like:

Vue CLI v3.11.0  
┌───────────────────────────┐  
│  Update available: 4.1.2  │  
└───────────────────────────┘  
? Please pick a preset: Manually select features  
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)  
>(*) Babel  
 ( ) TypeScript  
 ( ) Progressive Web App (PWA) Support  
 ( ) Router  
 ( ) Vuex  
 ( ) CSS Pre-processors  
 (*) Linter / Formatter  
 ( ) Unit Testing  
 ( ) E2E Testing

This screen is presented when we choose Manually Select Features . We can choose Default if we don’t want to choose anything from this screen.

To run the Vue UI, we can run:

npx vue ui

Then our browser will automatically go to http://localhost:8000/project/select, where we see a Create link to create a project.

We can then create a project by clicking Create a new project here once we clicked on the Create tab.

Conclusion

We can create a new Vue.js app by including it via a script tag or using the Vue CLI or the Vue UI web app.

To get started, we added Vue.js with a script tag and then create a new Vue instance to create an app.

There are various builds of the Vue.js framework. If we need templates, we need the full build unless it’s prebuilt with vue-loader or vueify .

Otherwise, we can use the runtime-only build to reduce the size of it.

Categories
JavaScript React

Add Captchas to a React App with reaptcha

Captchas stands for ‘Completely Automated Public Turing test to tell Computers and Humans Apart’. It’s often used to prevent automated traffic from tampering with websites.

With React, we can easily add a captcha to our app by using the reaptcha package. It’s very easy to use.

Installation

We can install it by running:

npm install --save reaptcha

We can also use yarn to install it y running:

yarn add reaptcha

Basic Usage

We can use it by signing up for a Recaptcha API key so that we can use Google’s Recaptcha service to use component. It works by injecting the Recaptcha scripts into our React app.

To sign up for an API key pair, go to https://www.google.com/recaptcha/ to sign up for an API key for free.

When we sign up for a key, we should sign up for a V2 Recaptcha key and add the domain that we want our Recaptcha widget to work on by entering the domain without any ports or child paths.

Once we signed up for an API key pair, we click Copy Site Key to copy the key that’s used on client side.

Next, we create our React app project and then write the following code:

import React from "react";
import Reaptcha from "reaptcha";

export default function App() {
  const [verified, setVerified] = React.useState(false);

  const onVerify = e => {
    setVerified(true);
  };

  return (
    <div className="App">
      <form>
        <Reaptcha
          sitekey="your_key"
          onVerify={onVerify}
        />
        <button type="submit" disabled={!verified}>
          Submit
        </button>
      </form>
    </div>
  );
}

In the code above, we put in our key as the value of siteKey. Then we have the onVerify callback, which is called when the captcha displayed is verified.

The onVerifed function is the callback that’s called when the captcha is successfully verified. Therefore, we use call setVerified there to enable the Submit button.

If we get an error, check if our domain is entered corrected in the API key settings. Also, we must be using the V2 version of reCAPTCHA with this package.

Once we did that, we should see a captcha, which enables the Submit button when we verified the displayed captcha.

Loading Captcha Manually

Reaptcha can also load captchas only when the user explicity does something to make it load.

We have to call the captcha’s renderExplicitly method to load the captcha. For instance, we can do that as follows:

import React from "react";
import Reaptcha from "reaptcha";

export default function App() {
  const [verified, setVerified] = React.useState(false);
  const [captchaReady, setCaptchaReady] = React.useState(false);
  const captcha = React.createRef();
  const onVerify = e => {
    setVerified(true);
  };

  const onLoad = () => {
    setCaptchaReady(true);
  };

  return (
    <div className="App">
      <button
        disabled={!captchaReady}
        onClick={() => {
          captcha.current.renderExplicitly();
        }}
      >
        Render reCAPTCHA
      </button>
      <form>
        <Reaptcha
          onLoad={onLoad}
          sitekey="your_key"
          onVerify={onVerify}
          ref={captcha}
          explicit
        />
        <button type="submit" disabled={!verified}>
          Submit
        </button>
      </form>
    </div>
  );
}

In the code above, we have a button to load the captcha when it’s clicked. It’s only enabled with then captcha script is finished loading so we can call the renderExplicitly method to load it.

In the Reaptcha component, we added the onLoad prop that calls the onLoad method. which calls setCaptchaReady to set the captchaReady property totrue` to enable the button.

Once is captcha is ready and the user clicks the Render reCAPTCHA button, we call captcha.current.renderExplicitly(); where captcha is the ref that we referenced in Reaptcha.

Most importantly, we added the explicit prop so that the captcha has to be loaded with an explicit user action.

Invisible Captchas

Reaptcha also supports invisible captchas. We can set the size prop to be invisible to make an invisible captcha.

For instance, we can create an invisible captcha as follows:

import React from "react";
import Reaptcha from "reaptcha";

export default function App() {
  const [verified, setVerified] = React.useState(false);
  const captcha = React.createRef();
  const onVerify = e => {
    setVerified(true);
  };

  return (
    <div className="App">
      <button
        onClick={() => {
          captcha.current.execute();
        }}
      >
        Execute reCAPTCHA
      </button>
      <form>
        <Reaptcha
          sitekey="your_key"
          onVerify={onVerify}
          ref={captcha}
          size="invisible"
        />
        <button type="submit" disabled={!verified}>
          Submit
        </button>
      </form>
    </div>
  );
}

We have to create a key for the V2 Invisible Captcha so that we can incorporate invisible captchas into our app.

Then we call captcha.current.execute(); where captcha is the ref for the Reaptcha component.

Methods

We can call the reset method on the Reaptcha ref to reset the reCAPTCHA instance and getResponse methos to return the response from reCAPTCHA. They both return promises.

Other Options

Other options that we can pass into the Reaptcha component as props include:

  • tabindex – HTML tab index
  • inject – boolean to indicate whether we want to inject the captcha script to the DOM automatically.
  • isolated – boolean to indicate that this component shouldn’t interfere with existing reCAPTCHA installations on a page
  • onError – error handler
  • children – a function to access instance methods without the need to use refs.

Conclusion

Reaptcha is an easy to use React component for incorporating the V2 reCAPTCHA script into our app. All we have to do is to add the component, sign up for the reCAPTCHA API key and then set a few options to get the captcha added to our React app.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.