【问题标题】:Can't deploy my Node.js app to Heroku, but it works locally无法将我的 Node.js 应用程序部署到 Heroku,但它可以在本地运行
【发布时间】:2017-12-18 15:53:53
【问题描述】:

我有一个非常简单的 Angular 2 的 Node.js 应用程序,我想将它部署在 Heroku 上。我成功部署了它(在我的假设中),但我无法在浏览器中访问它。

我如何部署我的应用程序:

1. mongoose.connect('mongodb://mardon:mardon@ds011863.mlab.com:11863/meanapp') // 将我的本地数据库更改为 mLab
2. 从 auth.services.ts 中删除所有本地域
3.<base href="./">//将index.html文件中的/替换为/.
4.const port = process.env.PORT || 8080;//添加process.env.PORT
5. ng build // 编译应用
6. git add . // 阶段性更改
7. git commit -am "some message" // 提交的更改
8. heroku create // 创建 heroku 应用
9. git push heroku master // 推送到 heroku
10. heroku open // 打开heroku
这就是我得到的


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:mardon@ds011863.mlab.com: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


我的代码有什么问题? 任何帮助,将不胜感激。

【问题讨论】:

    标签: node.js angular heroku


    【解决方案1】:

    应用程序正在运行,这个“未找到”页面是由 Express 生成的。我的猜测是您的文件路径错误。看看这个:

    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'));
    });
    

    path.join 方法存在,因此您无需自行连接字符串。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      这就是答案。

      1. 在我的应用程序中打开公用文件夹。

      2. ng build --prod --output-path /**path for public folder**/ // 编译了我的 Angular 项目(如果不行,就用ng build --prod 编译,然后把每个文件都剪切粘贴到公共文件夹)

      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'));    
      })
      

      一点点改变了我的 index.js 文件

      4.在core文件夹中创建Procfile。然后在其中添加web: node index.js

      5.如果编译angular有问题(例如:ERROR Property 'authService'是私有的,只能在类'NavbarComponent'中访问。),只需将private authService: AuthService替换为public authService:身份验证服务。 6. 部署如上图

      【讨论】:

        猜你喜欢
        • 2021-03-14
        • 2021-08-29
        • 2012-10-30
        • 1970-01-01
        • 2019-06-17
        • 1970-01-01
        • 2017-12-05
        • 1970-01-01
        相关资源
        最近更新 更多