2017-01-19 3 views
0

Так, как упоминалось в названии, у меня был этот проект, работающий на моем локальном хосте, но с тех пор, как я развернулся к героку, это не так. Я все еще могу получить доступ к DB через api и отобразить json, но файл переднего конца не работает.Restful API работает локально, но угловой интерфейс не работает при развертывании в heroku

На главной странице я просто получить не GET/

Server.js

'use strict' 
 

 
const express = require('express'); 
 
const app = express(); 
 
const bodyParser = require('body-parser'); // req.body 
 
const cors = require('cors'); // 8080 
 
const mongoose = require('mongoose'); 
 
const uriUtil= require('mongodb-uri'); 
 
let patients = require('./data'); 
 

 
const mongodbUri = 'mongodb://*********:***********@ds056009.mlab.com:56009/pt-db'; 
 
const mongooseUri = uriUtil.formatMongoose(mongodbUri); 
 
const dbOptions = {}; 
 

 
app.use(bodyParser.json()); 
 
app.use(bodyParser.urlencoded({ extended: true})); 
 
app.use(cors()); 
 

 

 

 
//app.get('/', function(req, res) { 
 
    //res.sendFile(__direname + '/index.html') 
 
//}); 
 

 
app.use('/api/patients', require('./api/patients/routes/post_patient')); 
 
app.use('/api/patients', require('./api/patients/routes/get_patients')); 
 
app.use('/api/patients', require('./api/patients/routes/get_patient')); 
 
app.use('/api/patients', require('./api/patients/routes/put_patient')); 
 
app.use('/api/patients', require('./api/patients/routes/delete_patient')); 
 

 

 
const PORT = process.env.PORT || 3000; 
 

 
app.listen(PORT,() => { 
 
    mongoose.connect(mongooseUri, dbOptions, (err) => { 
 
    if (err) { 
 
     console.log(err); 
 
    } 
 
    console.log(`Our app is running on port ${ PORT }`); 
 
    }); 
 
});

общественные/JS/app.js

(function() { 
 
    'use strict'; 
 

 
    var app = angular.module('patientsApp', []); 
 

 
    app.controller('patientsController', function($scope, $http) { 
 

 
     $http.get('api/patients') 
 
     .then(function(response) { 
 
      $scope.patients = response.data; 
 
     }); 
 
    
 
     $scope.savePatient = function(patient) { 
 
     $http.post('api/patients', patient) 
 
      .then(function(response) { 
 
      $scope.patients.push(response.data); 
 
     }); 
 
     } 
 
     
 
    }); 
 
})();

общественный/index.html

<!DOCTYPE html> 
 
<html ng-app="patientsApp"> 
 
<head> 
 
    <title>Patient DB</title> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
</head> 
 
    <body ng-controller="patientsController"> 
 

 
    <div class="container"> 
 

 
     <div class="col-sm-6"> 
 
     <form ng-submit="savePatient(patient)"> 
 
      <div class="form-group"> 
 
      <input type="text" placeholder="First Name" ng-model="patient.first_name" class="form-control"> 
 
      </div> 
 
      <div class="form-group"> 
 
      <input type="text" placeholder="Last Name" ng-model="patient.last_name" class="form-control"> 
 
      </div> 
 
      <div class="form-group"> 
 
      <input type="text" placeholder="Hospital Number" ng-model="patient.hosp_num" class="form-control"> 
 
      </div> 
 
      <div class="form-group"> 
 
      <input type="text" placeholder="Consultant" ng-model="patient.consultant" class="form-control"> 
 
      </div> 
 
      <div class="form-group"> 
 
      <input type="text" placeholder="Treatment Site" ng-model="patient.treat_site" class="form-control"> 
 
      </div> 
 
      <div class="form-group"> 
 
      <input type="text" placeholder="Treatment Group" ng-model="patient.treat_group" class="form-control"> 
 
      </div> 
 
      <button type="submit" class="btn btn-primary">Submit</button> 
 
     </form> 
 
     </div> 
 

 
     <div class="col-sm-6"> 
 
     <ul class="list-group"> 
 
      <li class="list-group-item" ng-repeat="patient in patients"> 
 
      <h4>Patient Name: {{patient.first_name + ' ' + patient.last_name}}</h4> 
 
      <p>Hospital Number: {{patient.hosp_num}}</p> 
 
      <p>Consultant: {{patient.consultant}}</p> 
 
      <p>Treatment Site: {{patient.treat_site}}</p> 
 
      <p>Treatment Group: {{patient.treat_group}}</p> 
 
      </li> 
 
     </ul> 
 
     </div> 
 

 
    </div> 
 

 
    <script src="node_modules/angular/angular.js"></script> 
 
    <script src="/app.js"></script> 
 
    </body> 
 
</html>

API/пациенты/gets_patients.js

const express = require('express'); 
 
const mongoose = require('mongoose'); 
 
const Patient = require('../model/Patient'); 
 
const router = express.Router(); 
 

 
router.route('/') 
 
    .get((req, res) => { 
 

 
    Patient.find({}, (err, patients) => { 
 
     if (err) { 
 
     res.status(400).json(err); 
 
     } 
 
     res.json(patients); 
 
    }); 
 
    
 
    }); 
 

 
module.exports = router;

Надеется, что это имеет смысл, любая помощь будет быть gre очень оценили.

+0

Измените свой адрес от «апи /» до «/ API /» в angular –

+0

Вы обслуживаете файлы anguar через ваш nodeJs-сервер? –

+0

Хм, я так думаю. – MojoJojo86

ответ

0
  1. Основная проблема, почему вы index.html не загружались, было связано с тем, что вы прокомментировали свое промежуточное программное обеспечение, которое служит вашему index.html.

  2. Теперь, когда ваш index.html обслуживается, он не может получить файл angular.js, потому что папке node_modules должно быть установлено значение static для бэкэнда узла для обслуживания файлов.

Вы можете сделать это следующим образом:

var path = require('path');//Require the nodeJs's path module. 
app.use('/', express.static(path.join(__dirname+'/node_modules')));//declare as static the node_modules folder so that node can serve the angular.js file inside it 

EDIT:

app.use('/', express.static(path.join(__dirname+"/public"))); 

служат также общую папку /, которая имеет остальную часть файлов таким же образом, как описано выше.

служить файл в angular.js через КДС или создать bundle.js с помощью Webpack или gulp..serving node_modules будет боль ..

+0

, и это на сервере server.js да? – MojoJojo86

+0

да. В server.js непосредственно перед //app.get ('/ ', function (req, res) { //res.sendFile(__direname +' /index.html ') //}); –

+0

Хмм все еще не работает, хотя я благодарен за вашу помощь. Не могли бы вы внести код в репозиторий git? https://github.com/MojoJojo86/ptdb – MojoJojo86

Смежные вопросы