【问题标题】:Why can't localhost find bundle.js even though it is in the public directory?为什么 localhost 即使在公共目录中也找不到 bundle.js?
【发布时间】:2019-12-11 23:11:55
【问题描述】:

我正在尝试创建一个已经为我创建了 server.coffee 文件的 react 应用程序。我设置了 babel 和 webpack 并创建了我的 index.js 和 app.js 文件。我在 index.html 上添加了 bundle.js 的脚本标签。当我在 localhost 上运行服务器时,我不断收到错误消息:加载资源失败:服务器响应 bundle.js:1 的状态为 404(未找到)。我在本地目录中看到该文件。我错过了什么?

HTML 文件:

<!DOCTYPE html>
<html>
  <head>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link href="/static/base.css" rel="stylesheet">
    <script defer src="./bundle.js"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

我的网页包:

module.exports = {
  entry: ['@babel/polyfill','./client/index.js'],
  mode: 'development',
  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  devtool: 'source-maps',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
}

我的.babelrc:

{
  "presets": ["@babel/preset-react", "@babel/preset-env"]
}

我的目录结构:

client
|-index.js
|-App.js
public
|-bundle.js
|-index.html
.babelrc
package.json
server.coffee
webpack.config.js

这是我正在运行的脚本:

  "scripts": {
    "start": "coffee server.coffee",
    "start-dev": "webpack -w & coffee server.coffee"
  }

最后这是我 server.coffee 文件中的 app.get:

# Default public
app.get '/', (req, res) ->
  res.sendFile __dirname + '/public/index.html'

这又是我遇到的错误。 GET http://localhost:3000/bundle.js net::ERR_ABORTED 404(未找到)

终端上没有编译错误或任何东西。只有控制台错误。任何帮助表示赞赏!我知道如何完成项目的其余部分,但如果不运行 React 是不可能的。

【问题讨论】:

  • 错误告诉你问题到底出在哪里——找不到文件,我认为你没有为 bundle.js 正确配置服务器端代码——你的 html 代码试图从 ./bundle 访问它.js 但在您的 webpack 配置中,bundle.js 的路径位于 public/
  • 是的,但我的 index.html 文件位于同一个文件夹(公共)中,所以我认为您可以使用相对路径。 bundle.js 在我的 vscode 目录中,但似乎没有提供给浏览器/可访问
  • 使用 server.coffee 中的代码,将 bundle.js 与 index.html 放在同一文件夹中不会自动使 bundle.js 可通过 ./bundle.js 访问

标签: javascript node.js reactjs coffeescript


【解决方案1】:

您需要在app.get() 路由之前使用express.static()

app.use(express.static('public'))

或者在 Coffeescript 中

app.use express.static 'public'

【讨论】:

  • 感谢您的输入,但我很抱歉不想包含完整的服务器文件# Initialize static file app.use '/static', express.static 'public' # Default public route app.get '/', (req, res) -&gt; res.sendFile __dirname + '/public/index.html'
  • 这只会使“公共”文件夹公开
  • 我添加了它但仍然没有 :( # Initialize static file middlware app.use '/static', express.static 'public' app.use express.static 'public' # Default public route app.get '/', (req, res) -&gt; res.sendFile __dirname + '/public/index.html' 奇怪的是 bundle.js 正在创建。我只是在浏览器中看不到它被厌倦了。所以如果我去开发.tools。没有可用的脚本文件。
  • 用咖啡脚本更新答案
  • 这成功了!谢谢你。所以本质上你是说第一行只创建了文件夹,而添加的行告诉它使用它?我想只是想确保我理解它为什么解决了这个问题。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 2023-03-18
  • 2018-12-21
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多