【发布时间】: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