Accessing the Angular/Node application with JWT token deployed to Heroku is unauthorized

  angular, express, github, heroku, node.js

Hi I have connected my angular application with Node/Express application. At first Angular was running at 4200 and Node was running at 3000, Now both the applications are running successfully in localhost:3000. This application is having JWT token authentication. I have deployed the application in Heroku, when I try to access the URL it is showing Unauthorized

I used the command ng run build, dist folder is created with index.html and other stuffs, when I try to commit the code in GitHub the dist folder and files inside this folder is not getting committed.

Everything is working fine in localhost.

app.js

require('dotenv').config()
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
const jwt = require('jsonwebtoken')
const bodyParser = require('body-parser');
require("./model/db");

const apiRouter = require("./routes/userRoutes");
const apiInvtRouter = require("./routes/inventoryRoutes");
const loginRouter = require('./routes/loginRoutes');
const signupRouter = require('./routes/signupRoutes');
const { isRegExp } = require('util');
const { signupUser } = require('./controller/signupController');

var app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.use(express.static(path.join(__dirname,'partystore_frontend-master/dist/frontend-partystore/index.html', 'build')))
// app.use(express.static(__dirname +"/partystore_frontend-master/dist/frontend-partystore/index.html"));

app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());



//access other end points of api
app.use((req, res, next) => {

  const authHeader = req.headers['authorization'];
  const refreshToken = req.headers['x-refresh-token'];
  const token = authHeader && authHeader.split(" ")[1]

  if (req.url === "/login/user" || req.url === "/signup/user") next();
  else if (token == null) return res.sendStatus(401);
  else {

    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (error, user) => {

      if (error) {

        return res.sendStatus(403)
      }

      req.user = user;
      next();
    });
  }
});

// app.get('/', (req,res) => {
//   res.sendFile(process.cwd()+"/partystore_frontend-master/dist/frontend-partystore/index.html")
// });


//login user
app.use('/login', loginRouter);
app.use('/signup', signupRouter);

app.use("/api/users", apiRouter);
app.use("/api/inventories", apiInvtRouter);
app.use(cors());

app.set('view engine', 'jade');


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});


// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



module.exports = app;


angular.json


{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "frontend-partystore": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/frontend-partystore",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "node_modules/font-awesome/css/font-awesome.css",
              "src/styles.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "frontend-partystore:build",
            "proxyConfig": "proxy.config.json"
          },
          "configurations": {
            "production": {
              "browserTarget": "frontend-partystore:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "frontend-partystore:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "frontend-partystore:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "frontend-partystore:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "frontend-partystore"
}


package.json

{
  "name": "frontend-partystore",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node app.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --prod"
  },
  "private": true,
  "proxy": "https://party-store-api.herokuapp.com",
  "dependencies": {
    "@angular/animations": "~11.0.1",
    "@angular/common": "~11.0.1",
    "@angular/compiler": "~11.0.1",
    "@angular/core": "~11.0.1",
    "@angular/forms": "~11.0.1",
    "@angular/localize": "~11.0.1",
    "@angular/platform-browser": "~11.0.1",
    "@angular/platform-browser-dynamic": "~11.0.1",
    "@angular/router": "~11.0.1",
    "@ng-bootstrap/ng-bootstrap": "^8.0.0",
    "bootstrap": "^4.5.3",
    "font-awesome": "^4.7.0",
    "jquery": "^3.5.1",
    "jw-angular-pagination": "^1.2.0",
    "ngx-pagination": "^5.0.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.10.2",
    "@angular/cli": "~11.0.2",
    "@angular/compiler-cli": "~11.0.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.1100.2",
    "@angular/cli": "~11.0.2",
    "@angular/compiler-cli": "~11.0.1",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  },
  "engines": {
    "node": "12.x",
    "npm": "6.x"
  }
}


proxy.config.json

{
    "/api": {
        "target": "https://party-store-api.herokuapp.com/",
        "secure": false
    }
}

Heroku Logs

2021-03-30T22:27:40.573585+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=party-store-api.herokuapp.com request_id=b7915e8f-5ba6-42d3-8408-bdae5fa13336 fwd="99.251.102.126" dyno=web.1 connect=1ms service=3ms status=401 bytes=254 protocol=https
2021-03-30T22:30:42.000000+00:00 app[api]: Build started by user [email protected]
2021-03-30T22:31:00.304859+00:00 app[api]: Release v36 created by user [email protected]
2021-03-30T22:31:00.304859+00:00 app[api]: Deploy 513aed41 by user [email protected]
2021-03-30T22:31:01.000000+00:00 app[api]: Build succeeded
2021-03-30T22:31:01.322210+00:00 heroku[web.1]: Restarting
2021-03-30T22:31:01.325040+00:00 heroku[web.1]: State changed from up to starting
2021-03-30T22:31:02.313440+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2021-03-30T22:31:02.428831+00:00 heroku[web.1]: Process exited with status 143
2021-03-30T22:31:04.776072+00:00 heroku[web.1]: Starting process with command `npm start`
2021-03-30T22:31:11.929999+00:00 app[web.1]: 
2021-03-30T22:31:11.930063+00:00 app[web.1]: > [email protected] start /app
2021-03-30T22:31:11.930064+00:00 app[web.1]: > node ./bin/www
2021-03-30T22:31:11.930064+00:00 app[web.1]: 
2021-03-30T22:31:12.816683+00:00 app[web.1]: into loginRoutes
2021-03-30T22:31:12.828290+00:00 app[web.1]: (node:23) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
2021-03-30T22:31:12.864734+00:00 app[web.1]: (node:23) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
2021-03-30T22:31:13.216199+00:00 heroku[web.1]: State changed from starting to up
2021-03-30T22:31:13.085946+00:00 app[web.1]: Mongoose db connected :  mongodb+srv://Prawin:[email protected]/test
2021-03-30T22:31:20.290732+00:00 heroku[router]: at=info method=GET path="/" host=party-store-api.herokuapp.com request_id=e7af5dba-f178-4d7e-9215-d71fe71c5a72 fwd="99.251.102.126" dyno=web.1 connect=1ms service=19ms status=401 bytes=254 protocol=https
2021-03-30T22:31:20.410562+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=party-store-api.herokuapp.com request_id=e8d44ac8-4035-4dfc-8195-9b0cb01a4082 fwd="99.251.102.126" dyno=web.1 connect=1ms service=3ms status=401 bytes=254 protocol=https
2021-03-30T22:31:20.294333+00:00 app[web.1]: [0mGET / [33m401 [0m4.542 ms - 12[0m
2021-03-30T22:31:20.412185+00:00 app[web.1]: [0mGET /favicon.ico [33m401 [0m0.620 ms - 12[0m
2021-03-30T22:31:21.731876+00:00 heroku[router]: at=info method=GET path="/" host=party-store-api.herokuapp.com request_id=9352b6a8-86dc-4444-9b7a-1c8f015134a3 fwd="99.251.102.126" dyno=web.1 connect=0ms service=9ms status=401 bytes=254 protocol=https
2021-03-30T22:31:21.731729+00:00 app[web.1]: [0mGET / [33m401 [0m0.847 ms - 12[0m
2021-03-30T22:31:21.840211+00:00 app[web.1]: [0mGET /favicon.ico [33m401 [0m8.177 ms - 12[0m
2021-03-30T22:31:21.838855+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=party-store-api.herokuapp.com request_id=80c9181d-631e-45db-9027-632c407b227a fwd="99.251.102.126" dyno=web.1 connect=0ms service=15ms status=401 bytes=254 protocol=https

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.