m_rd_n
m_rd_n

Reputation: 174

Can't deploy my Node.js app to Heroku, but it works locally

I have a quite simple Node.js app with angular 2 and want to deploy it on Heroku. I deployed it successfully (In my assumption) but i can't access it in the browser.

How I deployed my app:

1. mongoose.connect('mongodb://mardon:[email protected]:11863/meanapp') // changed my local db to mLab
2. removed all local domain from auth.services.ts
3. <base href="./">// replaced / with /. in index.html file
4. const port = process.env.PORT || 8080;// added process.env.PORT
5. ng build // compiled the app
6. git add . // staged changes
7. git commit -am "some message" // commited changes
8. heroku create // created heroku app
9. git push heroku master // pushed to heroku
10. heroku open // opened the heroku
and here is what I got


The app is not found


{
  "name": "mean-stack",
  "version": "1.0.0",
  "description": "\"# MEAN-stack-with-angular-2\"",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/mard-one/MEAN-stack-with-angular-2.git"
  },
  "author": "Mardon",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/mard-one/MEAN-stack-with-angular-2/issues"
  },
  "homepage": "https://github.com/mard-one/MEAN-stack-with-angular-2#readme",
  "dependencies": {
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "json-web-token": "^2.1.3",
    "mongoose": "^4.11.1"
  }
}

package.json


const express = require('express');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');

const router = require('./routes/authentication');
const config = require('./config/database');


const app = express();

const port = process.env.PORT || 8080;

mongoose.connect(config.uri, (err) => {
  if(err){
    console.log("Could NOT connect to database: ", err);
  } else {
    console.log("Connected to database: " + config.uri);
  }
});

// const corsOptions = {
//   origin: 'http://localhost:4200',
// }
// app.use(cors(corsOptions));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client/dist/'));
app.use('/authentication', router);


app.get('*', function(req,res) {
  res.sendFile(path.join(__dirname + '/client/dist/index.html'));
});



app.listen(port, function() {
  console.log("Listening on port " + port);
})

index.js


const crypto = require('crypto').randomBytes(256).toString('hex');

module.exports = {
  uri : 'mongodb://mardon:[email protected]:11863/meanapp',
  secret : crypto,
  db : 'mean-angular-2'
}

./config/database.js


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Client</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <base href="./">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="polyfills.bundle.js"></script><script type="text/javascript" src="styles.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script></body>
</html>

./client/dist/index.html


import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { tokenNotExpired } from 'angular2-jwt';

import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  // domain = 'http://localhost:8080';
  authToken;
  user;
  options;

  constructor(private http: Http) { };

  cleateAuthenticationHeaders(){
    this.loadToken();
    this.options = new RequestOptions({
      headers: new Headers({
        'Content-type': 'application/json',
        'authorization': this.authToken
      })
    })
  };

  loadToken(){
    const token = localStorage.getItem('token');
    this.authToken = token;
  };

  registerUser(user){
    return this.http.post('authentication/register', user).map( res => res.json());
  };
  checkEmail(email){
    return this.http.get('authentication/checkEmail/' + email).map( res => res.json());
  };
  checkUsername(username){
    return this.http.get('authentication/checkUsername/' + username).map( res => res.json());
  };
  login(user){
    return this.http.post('authentication/login', user).map(res => res.json());
  };


  storeUserData(token, user){
    localStorage.setItem('token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  };
  getProfile(){
    this.cleateAuthenticationHeaders();
    return this.http.get('authentication/profile', this.options).map(res => res.json());
  };

  logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  };
  loggedIn(){
    return tokenNotExpired();
  };
}

client/src/app/services/auth.service.ts


what is wrong with my code? Any help would be appreciated.

Upvotes: 0

Views: 859

Answers (2)

Lu&#237;s Brito
Lu&#237;s Brito

Reputation: 1772

The application is running, this "Not found" page is generated by Express. My guess is that you have a wrong path to your file. Check this out:

app.get('*', function(req,res) {
  // WRONG: res.sendFile(path.join(__dirname + '/client/dist/index.html'));

  // Correct!
  res.sendFile(path.join(__dirname, './client/dist/index.html'));
});

The path.join method exists so you don't need to concat strings on your own.

Hope it helps.

Upvotes: 1

m_rd_n
m_rd_n

Reputation: 174

Here is the answer.

1. opened public folder in my app.

2. ng build --prod --output-path /**path for public folder**/ // compiled my angular project ( if it does not work, just compile it by ng build --prod and cut and paste every file to the public folder)

3.

const express = require('express');    
const path = require('path');    
const app = express();    

const port = process.env.PORT || '8080';
app.set('port', port);

app.use(express.static(__dirname + '/public'));

app.get('/[^\.]+$', function(req, res) {    
  res.set('Content-Type', 'text/html')    
     .sendFile(path.join(__dirname, '/public/index.html'));    
});

app.listen(app.get('port'), function() {    
  console.log("Listening on port " + app.get('port'));    
})

little bit changed my index.js file

4. created Procfile in the core folder. Then added web: node index.js into it.

5. if there is a problem with compiling angular(for example: ERROR Property 'authService' is private and only accessible within class 'NavbarComponent'.), just replace private authService: AuthService with public authService: AuthService. 6. Deployed as it shown above

Upvotes: 1

Related Questions