complete Angular/MEAN beginner here - sorry in advance if I have trouble understanding any of your responses. Recently, I tried creating a web application with the MEAN stack and I used the angular-cli to create a basic project structure (ng new appName
). When running npm start
(which used the angular-cli command, ng serve
) without any changes to the files, everything went just fine and the default "Welcome to My App!" page rendered.
But once I created my own server.js file and changed the start script to node start.js
, the <app-root></app-root>
component no longer rendered. There were no errors in the console or during npm start
, so I wasn't quite sure where to begin.
I checked on some forums and some users said that faulty HTML could be the reason. I replaced the entire template to simply "Testing", and yet nothing would load. Others said that I had to include the static path in my server.js file with app.use(express.static(path.join(__dirname, 'src')));
, but my components still would not render. I also noticed my Typescript files were not compiling to Javascript so I took care of that issue, but no avail.
I was thinking that I may be missing something in my server.js file that imports or renders the Angular components, but I can't seem to find any discrepancies between my file and samples on Github. My server.js file is posted below and hopefully someone with more experience than me can spot out what I may be missing.
var express = require("express");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var path = require("path");
var ObjectID = mongodb.ObjectID;
var api = require('./routes/api')
var app = express();
// Body Parser Middleware.
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'src')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'src/index.html'));
})
// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;
// Connect to the database before starting the application server.
mongodb.MongoClient.connect('the mongodb url goes here, but I have left it out for obvious security reasons', function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
via Diafotismos
No comments:
Post a Comment