Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step.

Your assistance would be highly valued as I aim to export the variable "nameid" from my routes.js file for use in an Angular component.

angular-master/express/config/routes.js

var xmldoc = require('xmldoc');
var DOMParser = require('dom-parser');
module.exports = function (app, config, passport) {

  app.get('/', function (req, res) {
      res.redirect('/home')
  });

  app.get('/login',
    passport.authenticate(config.passport.strategy,
      {
        successRedirect: '/',
        failureRedirect: '/login'
      })
  );

  app.post('/', function(req, res) {
    console.log('body saml:', req.body.SAMLResponse);
    const body = req.body.SAMLResponse;
    var b = new Buffer(body, 'base64');
let text = b.toString('ascii');
    //var inflated = pako.inflateRaw(b, {to:'string'}); 
    console.log('formmatted saml',text);
     var document = new xmldoc.XmlDocument(text);
 console.log('formmatted document',document);
     var status = document.descendantWithPath("samlp:Status").firstChild.attr;
    
   var attr = text.includes("AttributeStatement");
   var nameid = text.substring(text.lastIndexOf("<NameID>") + 8,text.lastIndexOf("</NameID>"));
   module.exports.nameid = nameid;
    console.log("status id:", status['Value']);
console.log(attr);
  console.log('LDAP DB username: ' + nameid);
  
  

};

angular-master/src/app/site/user-history/user-history.component.ts

import { Component, OnInit } from '@angular/core';
import { RouterLink } from '@angular/router';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { element } from 'protractor';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';

var routes = require('./../../../../express/config/routes.js');
    

@Component({
  selector: 'app-user-history',
  templateUrl: './user-history.component.html',
  styleUrls: ['../style.css']
})
export class UserHistoryComponent implements OnInit {


  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {}


  ngOnInit() {
  console.log(routes.nameid); 


}

The errors displayed in my console are as follows:

xmldoc.js:5 Uncaught ReferenceError: global is not defined
    at xmldoc.js:5
    at Object../node_modules/xmldoc/lib/xmldoc.js (xmldoc.js:339)
    at __webpack_require__ (bootstrap:76)
    at Object../node_modules/xmldoc/index.js (index.js:3)
    at __webpack_require__ (bootstrap:76)
    at Object../express/config/routes.js (routes.js:1)
    at __webpack_require__ (bootstrap:76)
    at Object../src/app/site/user-history/user-history.component.ts (user-history.component.ts:23)
    at __webpack_require__ (bootstrap:76)
    at Object../src/app/site/site.module.ts (main.js:8001)
(anonymous) @ xmldoc.js:5
./node_modules/xmldoc/lib/xmldoc.js @ xmldoc.js:339
__webpack_require__ @ bootstrap:76
./node_modules/xmldoc/index.js @ index.js:3
__webpack_require__ @ bootstrap:76
./express/config/routes.js @ routes.js:1
__webpack_require__ @ bootstrap:76
./src/app/site/user-history/user-history.component.ts @ user-history.component.ts:23
__webpack_require__ @ bootstrap:76
./src/app/site/site.module.ts @ main.js:8001
__webpack_require__ @ bootstrap:76
./src/app/app.module.ts @ app.component.ts:13
__webpack_require__ @ bootstrap:76
./src/main.ts @ environmentLoader.ts:21
__webpack_require__ @ bootstrap:76
0 @ main.ts:16
__webpack_require__ @ bootstrap:43
webpackJsonpCallback @ bootstrap:30
(anonymous) @ main.js:1

Answer №1

Whoops, it seems like import should be used instead of require.

import * as routes from './../../../../express/config/routes.js';
ngOnInit() {
  console.log(routes.nameid); 
}

But why are you trying to access a backend variable in the frontend? Remember, they operate on separate servers.

Answer №2

It is essential to recognize that Node.js functions as a server-side framework while Angular operates as a frontend framework, both requiring compilation.

Although they are both written in JavaScript, attempting to import server code into the frontend will not work with Angular's package.json and angular.json files as they do not recognize routes.js for compilation.

Angular is designed to be loaded within browsers using plain HTML and JavaScript.

To successfully integrate these frameworks, it is necessary to create an API.

Answer №3

global is the global object in Node.js, similar to window in a browser environment. This distinction is crucial as Node.js and browsers have separate environments - thus, attempting to access variables from one environment in another will result in errors.

Node.js code operates within its server-side runtime, whereas Angular code functions within the client-side browser environment. These distinct environments are unable to directly interact with each other's variables. Attempting to do so is simply not feasible or practical.

Answer №4

If you haven't already, consider trying a different tactic by importing only the specific variable you need instead of everything in your current approach.

Here's an example:

import { nameid } from './../../../../express/config/routes.js'

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

Stop extra properties from being added to the return type of a callback function in TypeScript

Imagine having an interface called Foo and a function named bar that accepts a callback returning a Foo. interface Foo { foo: string; } function bar(callback: () => Foo): Foo { return callback(); } Upon calling this function, if additional pr ...

Sit tight as we prepare all static assets for loading on the screen

Currently, I am developing a vuejs application that will incorporate video elements. To enhance user experience, we are interested in preloading these videos upon the initial loading of the web application. I am considering using a listener like, documen ...

Guidelines for incorporating Dropdown menus in a Multi-level Carousel themed SideNav using Angular 5 Material

Hey there, World! I've been working on a sidenav with tabs that has the perfect transition effect I was looking for. Now, I want to add functionality so that when users click on "Option 1, Option 2 or Option 3", the tab transitions into dropdowns with ...

The regex string parameter in node.js is not functioning properly for matching groups

The String.prototype.replace() method documentation explains how to specify a function as a parameter. Specifying a string as a parameter The replacement string can contain special patterns for inserting matched substrings, preceding and following portion ...

Leveraging data schemas to manage the feedback from APIs

I am curious about the benefits of modeling the API response on the client side. Specifically: First scenario: const [formData, setFormData] = useState(null); ... useEffect(() => { const callback = async () => { try { const fetchDa ...

Develop React routes on the fly

Currently, I am working on a React App that requires the creation of Routes dynamically based on data models sent by the backend in JSON format. For example: { "Route1": [ { "id": 1, "visible": true, "other_data": "..." } ], "Route3": [ { "i ...

I'm having trouble grasping the concept of this asynchronous behavior

After reviewing the output provided, my initial expectation was for working to be displayed between the lines of begin and end. Here is the rule: Is there a possible solution to achieve this outcome without modifying the app.js file? app.js const se ...

When a specific item is selected from a drop-down menu, text boxes and drop-downs will dynamically appear and change

In the current version of my code, there is a single drop-down menu with three options for the user to select from. If "Complete" is chosen, a text box should appear. If "Abandon" or "Transfer" is selected, a separate drop-down menu needs to be displayed. ...

having trouble transferring data from one angular component to another

I've been attempting to send data from one component to another using the service file method. I've created two components - a login component and a home component. The goal is to pass data from the login component to the home component. In the l ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

Angular pagination refers to the process of dividing a large

Currently utilizing ngx-pagination https://www.npmjs.com/package/ngx-pagination app.module: import { NgxPaginationModule } from 'ngx-pagination'; @NgModule({ declarations: [ AppComponent, ... ], imports: [ ... NgxPaginat ...

Is there a way to update an angular.js service object without using extend or copy?

I am working with 2 services and need to update a variable in the first service from the second service. Within a controller, I am assigning a scope variable to the getter of the first service. The issue I am facing is that the view connected to the cont ...

Moving the starting directory of a NodeJS application on Azure

My NodeJS app on Azure was initially written in Javascript with the app.js file located in the root directory. This file was automatically detected during deployment via Git. Recently, I converted the app to Typescript and now have a build directory, with ...

Adding Images Using Angular 8

I'm encountering difficulties with image upload in the file located at '../src/app/assets/'. Below is the Form I am using: <form [formGroup]="formRegister" novalidate=""> <div class="form-group"> <label for="ex ...

Searching for variables within files using Node.js and constructing an object from the results

Trying to figure out how to streamline this process. Here's the directory structure I'm working with: src/ modules/ clients/ i18n/ en-US.ts tasks/ i18n/ en-US.ts So, ea ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

Is there a way to stop a music track from playing?

function playMusic(){ var music = new Audio('musicfile.mp3'); if (music.paused) { music.play(); } else { music.pause(); } } <input type="button" value="sound" onclick="playMusic()" ...

What is the method for obtaining the current participant's ID from the Angular frontend of a Hyperledger Composer application?

Need help with hyperledger-composer: I know how to retrieve the id of the current participant within a transaction processor function using this code: let currentParticipant = getCurrentParticipant(); let participantId = currentParticipant.getFullyQuali ...

Add the mat-ripple effect to the host element with Angular 5 attribute directive

Is there a way to automatically include the mat-ripple directive on the host element of a custom directive I've made? The goal is to have mat-ripple added seamlessly to any element that uses my custom directive. For instance, when I add <button my ...

Summernote - When validating text, it is shown as raw HTML

I have integrated Codeigniter with Summernote on the frontend. In a form, if certain fields are left empty, the same page reloads for validation checking. The JavaScript and CodeIgniter code I am using is as follows: $(window).load(function(){ &l ...