0
votes

Read all the possible answers here in StackOverflow but still fighting with the problem. The app is deployed, but when trying to open it - white blank screen and error messages. It looks like js files return html file. It does not go further than html file..Locally with server 3000 the app works great. Deployment though is not working. Hopefully will get help on that.

runtime.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
polyfills.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
styles.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
scripts.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
vendor.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>CodingBlog</title>
  <base href="/codingBlog/">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="shortcut icon" type="image/png" href="/codingBlog/src/assets/logo.png">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- Fontawesome -->
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.7/css/all.css">
  <!--Devicon CSS for the Skills section--> 
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/konpa/devicon@master/devicon.min.css">
  <!-- Google Fonts "%7C" replaces "|" for w3c validation -->
  <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,300;0,400;1,700&display=swap" rel="stylesheet">



</head>
<body data-spy="scroll" data-target="#navbarResponsive">
  <div class="container">
  
   <app-root></app-root> 
 
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

app.js

var express = require('express')
var path = require('path')
var cors = require('cors')
var morgan = require('morgan')
var bodyParser = require('body-parser')
var serveStatic = require('serve-static')
const logger = require("morgan")

const mongoose = require('mongoose')
require('dotenv').config();
var app = express()

//step1
var PORT = process.env.PORT || 8080
var Users = require('./routes/users')
app.use(cors({
origin:['http://localhost:4200', 'http://127.0.0.1:4200'],
credentials:true}));


app.use(bodyParser.json())
app.use(logger('combined'))
app.use(
  bodyParser.urlencoded({
    extended: false
  })
)

const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost:27017/members"
mongoose
.connect (MONGODB_URI,
    { useNewUrlParser: true ,   
    useCreateIndex: true, 
    useUnifiedTopology: true,
    useFindAndModify: false

  })
  .then(() => console.log('MongoDB Connected Externally'))
  .catch(err => console.log('Could not connect to the DB', err))

  //Data parsing
  app.use(express.json())
  app.use(express.urlencoded({extended: false}))
  

app.use(morgan('tiny'))
app.use('/users', Users)

const Post = require('./model/post')
//API end point for fetching the list of blog posts. Since for db Mongo is used, Mongoose client added to connect the db with the app.
app.post('/api/post/getAllPost', (req, res) => {
    mongoose.connect(url, { useMongoClient: true }, { useUnifiedTopology: true },function(err){
      console.log(err - 'error here')
        if(err) throw err;
        console.log("connection established successfully")
        Post.find({},[],{ sort: { _id: -1 } },(err, doc) => {
            if(err) throw err;
            return res.status(200).json({
                status: 'success',
                data: doc
            })
        })
    });
})
//step3
if(process.env.NODE_ENV ==='production') {
 
  app.use(express.static("dist/codingBlog"));
  const allowed = [
    '.js',
    '.css',
    '.png',
    '.jpg'
  ];
  
  app.get('*', (req, res) => {
    if (allowed.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
      res.sendFile(path.resolve(`../codingBlog/dist/codingBlog/${req.url}`));
    }
    else {
    const app = path.join(__dirname, "../codingBlog/dist/codingBlog/");
    const index = path.join(__dirname, "../codingBlog/dist/codingBlog/", "index.html");
    res.sendFile(app);   
    res.sendFile(index);  
    } 
  })
  app.get('*', function (req, res) {
    res.redirect("/index.html")
       })
}



app.use((req, res, next) => {
  res.status(404).send({
  status: 404,
  error: "This page does not exist. You will have to check the correct routing"
  })
 })


app.listen(PORT, 
  console.log(`Server is running successfully at ${PORT}!`))
1

1 Answers

0
votes

I did find the solution. There was a similar problem here how to build static

The problem was the wrong path for static.Instead all of these

 app.get('*', (req, res) => {
if (allowed.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
  res.sendFile(path.resolve(`../codingBlog/dist/codingBlog/${req.url}`));
}
else {
const app = path.join(__dirname, "../codingBlog/dist/codingBlog/");
const index = path.join(__dirname, "../codingBlog/dist/codingBlog/", "index.html");
res.sendFile(app);   
res.sendFile(index);  
} })

I added

app.use(express.static(path.join(__dirname, "../codingBlog/dist")))