Getting a JWT token from Express to Angular using ngResource: A step-by-step guide

Currently, I am utilizing a jwt token for user registration validation. A unique URL is generated and sent to the user via email, which leads them to the authentication page. On the server side, the token is decoded and I need to transmit this JSON data to Angular on the client side. How can I achieve this by using the token as a query parameter and fetching it with ngResource?

server.js

'use strict';

var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var jwt = require('jsonwebtoken');
var moment = require('moment');

var port = process.env.PORT || 5000;

app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./.tmp'));
app.use('/*', express.static('./src/client/index.html'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Generating token with expiration time
var expires = moment().add(12, 'hours').valueOf();
var token = jwt.sign({
    user: 'userdata',
    iat: Math.floor(Date.now() / 1000),
    expireIn: expires
}, 'thisismysecretstring');


// Nodemailer sendMail function
app.post('/sendMail', function(req, res) {
  var transporter = nodemailer.createTransport('smtp://b204bf8f6ede15:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="efd8de8dda8cdedbd8dcd7dadd8addaf828e86839b9d8e9fc18680">[email protected]</a>:2525');
  var data = req.body;
  var mailOptions = {
    from: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e6e7faedf8e4f1c8e1f0eee1faeda6ebe7e5">[email protected]</a>',
    to: data.email,
    subject: 'Email sent by ' + data.displayName,
    html: '<p>Please click on url below to register</p><br><a href="http://localhost:3000/auth/?token='+token+'">CLICK HERE</a>'
  };
  transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
      return console.log(error);
    }
    console.log('Message sent: ' + info.response);
  });
  res.json(token);
});

// Decoding token from URL parameter
app.get('/auth', function(req, res) {
  var token = req.query.token;
      try {
          var decoded = jwt.verify(token, 'thisismysecretstring');
          if (decoded.exp <= Date.now()) {
            res.end('Access token has expired', 400);
          }
          res.json(decoded);
      } catch (err) {
          console.log(err);
          res.json(err);
      }
});

app.listen(port, function () {
  console.log('Express app listening on port: ' + port);
  console.log(__dirname);
});

token.js

(function() {
    'use strict';
    angular
        .module('xfire.token', ['ngResource'])
        .factory('Token', function($resource) {
            return $resource('auth/:token', {
                token: '@token'
            });
        });
})();

Example of url format:

http://localhost:3000/auth/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiZ2NmYWJyaSIsImlhdCI6MTQ2ODI0NDI1NCwiZXhwaXJlSW4iOjIxNjAwMDAwfQ.5rs1rlWMTTcap4idG-XOU-UiwbU0YzlnAYjm9Vwz-B0

Answer №1

My preferred method of sending it is through a header, typically labeled as x-auth-header.

However, I do not recommend using ngResource as it has limitations unless for experimentation purposes only.

Personally, I opt for restangular, utilizing request and response interceptors.

The response interceptor decodes the token while the request interceptor authorizes the request with "Bearer" + tokenString.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Emphasize today's date on the w3widgets adaptable calendar

While developing a website featuring a calendar to showcase events, I came across w3widgets, which proved to be quite helpful. However, I encountered an issue when trying to highlight the current date on the calendar. It seems that the calendar only highli ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

Scheduled tasks on Google Cloud Platform's App Engine are failing to run over the weekend

I am facing an issue with running a cron job in my node/express application using the node-cron library. The application is hosted on Google Cloud App Engine. My aim is to automate sending emails every day at 9 AM, but the cron seems to only work from Mon ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

What is the best way to save a JavaScript object or JSON within an HTML element using the HTML5 data attribute?

I have an anchor element and I want to store and retrieve the object within it in this specific format. <a id ="test" data-val="{key1:val1,key1:val1}"> </a> When saved in this manner, fetching it with $("#test").data('val') returns ...

Issue with jqLite's .triggerHandler() functionality not behaving as anticipated

I'm having an issue with a piece of code that uses triggerHandler. The event is being called correctly, but it's not working as expected. Below is the code snippet and a link to a jsFiddle : HTML: <body ng-app="app"> <button box-cr ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Using Vue to dynamically upload multiple files simultaneously

Although this question has been asked frequently, most of the answers do not address a key issue - how to upload multiple images while knowing which image belongs to which data. Attempting to bind v-model to input file doesn't work as expected, and ev ...

Arrays passed as query parameters to Next.js router.query may result in the value being

When trying to pass objects from an array to another page using router.query, individual objects like router.query.title work as expected. However, when attempting to pass arrays such as router.query.reviews, it returns something like reviews: ['&apos ...

Is the Ajax DataType response JSON showing as "OK" but the output is blank?

So, I'm facing a challenge here. I have a basic jQuery Ajax request that isn't working when I set the DataType to "JSON". var form_data = { "id": msg, "token": token }; $.ajax({ type: 'POST', url: "ajax.php", ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Issue - The module ./en.json could not be located when using the vue-i18n plugin

I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales with the correct ...

Node.js schedule randomizer

I'm trying to figure out how to call a function within a random range of time intervals in Node.js. What I need is for the function to run once between 2 and 12 hours, then again at another random interval between 2 and 12 hours, and so on. However, I ...

The MaterialUI table pagination feature is experiencing an issue where the "Next" button is

Every time I attempt to search for a record with a lower value, such as 6, 14, 19, or 20, the Next button does not become active. However, when dealing with larger records, it functions perfectly fine. I am uncertain about what mistake I might be making. ...

I'm curious about the equivalent of "ng serve" for nodejs. Do other languages have similar tools available?

ng serve has revolutionized my workflow. With a simple save, I can instantly see the changes in my Angular code reflected in the running instance of my project, allowing me to quickly iterate on my work. But why doesn't a similar tool exist for other ...

Can an image be uploaded and displayed on a mean.io nodeJS express server?

I've come across information stating that nodejs may not be the best choice for long running operations. Despite this, I am interested in building my application on mean.io (express and nodejs). Although node may not be optimal due to its long running ...