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

What is the process for creating a line using points in three.js?

Can anyone provide a solution for creating a straight line using new THREE.Points()? I attempted to place particles and set their positions with an array and for loop, but the spacing was inconsistent. ...

Unexpected token error occurs when using map-spread operator in vue-test-utils combined with jest

I recently set up testing for my Vue project by following the instructions provided in this helpful guide here Upon completion of the guide, I proceeded to create a test for one of my components. However, when I ran jest, I encountered the following error ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

The JQuery function fails to execute following a successful Ajax request

I recently ran into an issue with my Ajax call. Here's the code snippet in question: $("#start-upload-btn").click(function(){ $.ajax({ type: "post", url: "", data: { newProjectName: $('#project-name') ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

Refreshing the v-model in a child component

Within my parent component, the code structure is similar to this: <template> <ProductCounter v-model="formData.productCount" label="product count" /> </template> <script setup> const initialFormData = { ...

Having trouble retrieving all JSON properties

I am facing an issue with my json structure where I am unable to access certain properties. I can only access the main properties like type, properties, and so on within that hierarchy level. However, I cannot seem to access icon, iconURL, or title. The da ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

Error: Property 'config' cannot be accessed because it is null

Upon transferring my Angular project from my local computer to a Linux server, I attempted to launch the project using ng serve but encountered an issue where it opened a new file in the console editor instead. After some investigation, I tried running np ...

Retrieve a Vue Component by utilizing a personalized rendering method for a Contentful embedded entry

Currently experimenting with Contentful, encountering some issues with the Rich text content field. To customize the rendering of this block and incorporate assets and linked references in Rich text content, I am utilizing the modules '@contentful/ri ...

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

The absence of FormData.entries in submit is a limitation of the Vue framework

I recently created a Vue-App that consists of a simple form with just one <input name"surname"> and a <button type="submit">. The use case is to input "myname" and submit the form. However, when I initialize new FormData( ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Using the Tailwind CSS framework in combination with Vue's v-html

My vue component is designed to accept a prop of raw HTML, which originates from a wysiwyg editor utilizing tailwind classes for styling - similar to our vue app. The issue arises when using v-html="responseFromAPI" in my component, as the raw H ...

Having trouble with selecting checkboxes in a div using jQuery? While it may work in IE and Firefox, Chrome seems to be causing issues

In my div, I have several checkboxes placed under labels for formatting purposes. There is a list of checkbox names that need to be checked upon certain actions. Here is the list: var columns= ['2','5','4'] This is the curren ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Merge multiple Javascript files into one consolidated file

Organizing Files. /app /components /core /extensions - array.js - string.js /services - logger.js /lib - core.js Core.js (function() { 'use strict'; an ...

"Discover the step-by-step process of transforming an input field value into a checkbox with

I've been experimenting with creating a To-Do list using HTML, CSS, and Javascript. I've managed to capture the input field value in a fieldset so far. However, my goal is to find a way to transform the input field value from the textfield into a ...

AngularJS: updating a module

I recently started learning AngularJS and I need some guidance on how to refresh the data in a table within a module (specifically, a list of names and post codes). Below is the script where I am trying to reload the JSON file upon clicking a button: < ...