当前位置: 首页 > 知识库问答 >
问题:

Heroku Angular app部署:加载资源失败:服务器响应状态为404(未找到)

董宜然
2023-03-14

在StackOverflow中阅读所有可能的答案,但仍在与问题作斗争。应用程序已部署,但在尝试打开时-白色空白屏幕和错误消息。看起来js文件返回html文件。它不超过html文件。。在服务器3000本地,该应用程序运行良好。但部署不起作用。希望能得到帮助。

运行时。js:1加载资源失败:服务器响应状态为404(未找到)
。js:1加载资源失败:服务器响应状态为404(未找到)
。js:1加载资源失败:服务器响应状态为404(未找到)
脚本。js:1加载资源失败:服务器响应状态为404(未找到)
供应商。js:1加载资源失败:服务器响应状态为404(未找到)
main。js:1加载资源失败:服务器响应状态为404(未找到)
索引。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>

应用程序。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个答案

孟晨朗
2023-03-14

我确实找到了解决办法。这里也有一个类似的问题如何建立静态

问题是静态的错误路径。而不是所有这些

 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")))
 类似资料:
  • 当我将我的反应项目部署到Surge时,构建成功并且可以获取应用程序URL。但是当我链接到URL时,我可以在检查控制台中看到一个空白页面和一些错误: 这是我的包中的react start脚本。json文件。 和css文件的链接地址,导致错误

  • 我有angular 6应用程序在我的本地机器上,一切都按照我想要的完美工作,完成项目后我将其部署到heroku,当我运行我的应用程序时,这里是指向heroku中应用程序的链接:测试应用程序 正如您所看到的,我在控制台浏览器中遇到以下错误 加载资源失败:服务器响应状态为404(未找到) 这是我在github中的应用程序结构 github中的应用程序回购 为了快速参考,这里是服务器。js 这是hero

  • 我完全新的ReactJS。 我在YouTube遵循这个教程,遵循每个步骤。 直到我发现我的代码出现了这样的错误 因为我刚开始编程ReactJS,我仍然不明白该做什么,以及如何修复这个问题 本教程展示了如何构建一个简单的CRUD应用程序,内置于ReactJS和PostgreSQL 这里我提供我的应用程序。js代码 这是我的server.js代码: 我该怎么办?任何建议都能帮我解决这个问题 非常感谢。

  • 我有一个ReactJS应用程序,我正试图部署在heroku上。它在本地运行良好,但部署不正确!在页面上,我无法获得/ 应用程序链接:https://nameless-spire-06291.herokuapp.com/ 控制台错误:1。加载资源失败:服务器响应状态为404(未找到)2。拒绝加载图像的https://nameless-spire-06291.herokuapp.com/favicon

  • 我正在学习Lynda关于Javascript和Ajax以及hungup的教程,主题是“使用同步XHR请求”。 html文件基本上是: javascript文件为: data.txt文件上有“Hello World”。 项目文件的路径为 当我打开wampserver上的localhost并执行inspect元素时,我得到了上面的错误:“未能加载资源:服务器响应状态为404(not found)” 不

  • 我收到错误:“加载资源失败:服务器响应状态为404(未找到)”,javascript文件中有图标文件。 试图得到一个标记显示在谷歌地图。 我正在使用Visual Studio 2015和Apache Cordova。 文件位于www/scripts/googlemap。js和www/scripts/green。巴布亚新几内亚。 编辑:主要问题是来源。Url应为/scripts/green。png或