Heroku Angular应用程序部署:无法加载资源:服务器以状态404响应(未找到)

时间:2020-07-24 22:06:27

标签: angular mongodb heroku deployment mean-stack

在此处阅读StackOverflow中所有可能的答案,但仍在解决问题。该应用已部署,但是在尝试打开它时-白色黑屏和错误消息。看起来js文件返回html文件。它不会超出html文件的范围。在服务器3000上本地运行的应用程序效果很好。部署虽然无法正常进行。希望能对此有所帮助。

runtime.js:1无法加载资源:服务器响应状态为404(未找到)
polyfills.js:1无法加载资源:服务器响应状态为404(未找到)
styles.js:1无法加载资源:服务器响应状态为404(未找到)
scripts.js:1无法加载资源:服务器的响应状态为404(未找到)
vendor.js:1无法加载资源:服务器的响应状态为404(未找到)
main.js:1无法加载资源:服务器响应状态为404(未找到)
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 个答案:

答案 0 :(得分:0)

我确实找到了解决方案。 how to build static

这里也存在类似的问题

问题是static的错误路径。 所有这些

 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.use(express.static(path.join(__dirname, "../codingBlog/dist")))