Achraf El Khamsi
Achraf El Khamsi

Reputation: 160

Angular app served by Node.js without JS scripts

I created an Angular app with a node.js server. When I serve the app locally ('ng serve'), the app works fine. However, when i build the Angular project into a 'public' folder, and set the node.js server to serve the web pages of the app, the browser displays the HTML code served by the server as text.

The node.js code that serves the pages is the following:

const express = require('express')
const app = express()
const server = require('http').createServer(app)
const bodyParser = require('body-parser')
const cors = require('cors')
const path = require('path')
const fs = require('fs')

const authRouter = require('./src/middlewares/auth.js');
const roomRouter = require('./src/middlewares/room.js');
const controller = require('./src/middlewares/token.js');

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

///////////////////////////////////////
//////////// MIDDLEWARES //////////////
///////////////////////////////////////

app.use(bodyParser.json()) //Parsed data is populated on the request object (i.e. req.body).
app.use(bodyParser.urlencoded( { extended: true }))
app.use( (req, res, next ) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Requested-With, Accept, x-access-token')
  if (req.method == 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH')
  }
  res.header('Content-Type', 'application/json') //REST-API: we only send back json data
  next()
})

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


//////////////////////////////
///////// DATABASE ///////////
//////////////////////////////
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/sync';
var db;
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(client => {
    console.log("connection to database established...  ");

    db = client.db("sync");
    db.createCollection('users'); //Normally, if it already exists, it shoudn't do anything, but I'm not sure

    app.use((req, res, next) => {
      req.db = db
      next();
    })

  })
  .catch(err => {console.log(err)})

///////////////////
//// ROUTING //////
///////////////////

app.use('/api/auth', authRouter)
app.use('/api/room', roomRouter)

app.get('*', (req, res) => {
   // res.setHeader('Content-Type', 'text/html')
   res.sendFile(path.join(__dirname, 'public', 'index.html'));
   // res.send('Hello')
});


///////////////////////////////////////
///////// SOCKET CONNECTION ///////////
///////////////////////////////////////

var sockets = [];

const io = require('socket.io').listen(server);

io.on('connection', (socket) => {
    //socket.on...
    //...
});


///////////////////////////////////////
///////// SERVER CONNECTION ///////////
///////////////////////////////////////

app.listen(PORT, () => {
  console.log("Running on port " + PORT)
})




The index.html file is the following:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Client2</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <script src="runtime-es2015.js" type="module"></script>
  <script src="runtime-es5.js" nomodule defer></script>
  <script src="polyfills-es5.js" nomodule defer></script>
  <script src="polyfills-es2015.js" type="module"></script>
  <script src="styles-es2015.js" type="module"></script>
  <script src="styles-es5.js" nomodule defer></script>
  <script src="vendor-es2015.js" type="module"></script>
  <script src="vendor-es5.js" nomodule defer></script>
  <script src="main-es2015.js" type="module"></script>
  <script src="main-es5.js" nomodule defer></script>
</body>
</html>

When I inspect the web page served by the server, only the index.html is sent and not the scripts linked to it, hence not being able to display the page correctly. it's as if express doesn't serve the javascript files.

Upvotes: 1

Views: 187

Answers (1)

sehe
sehe

Reputation: 420

res.sendFile() is an express function to send a file (https://expressjs.com/de/api.html#res.sendFile). So, the headers will be set accordingly. Use the express function res.send() to correctly set the response and look at http://expressjs.com/en/starter/basic-routing.html .

Even better: use a simple http-server like nginx oder the npm tool http-server for your serving purpose.

Upvotes: 1

Related Questions