表达# 39;response.sendFile()发送Uncaught SyntaxError: Unexpected

express' response.sendFile() sends Uncaught SyntaxError: Unexpected token <

本文关键字:Uncaught 发送 SyntaxError Unexpected response sendFile 表达      更新时间:2023-09-26

我使用react-router与browserHistory。这个函数:

app.get('*', function (request, response){
  response.sendFile(path.join(__dirname + "/public/index.html"))
})

应该发送Index.html,因为路由是在客户端使用react-router进行的。但不知何故,我的index。html被服务器误解了,我得到了这个错误:

Uncaught SyntaxError: Unexpected token <</p>

我不知道这是什么问题。文件路径错误?我的树是这样的:

/app
/app/myJavascriptStuff.js
/public
/public/index.html
/moreStuffThatsNotRelevant
/server.js <- my express file

如果没有上述功能,我的页面通常会响应:

Cannot GET/whatever

在localhost:3000(例如localhost:3000/其他)上刷新页面

因为我意识到我不擅长描述事物,这里有一个到存储库的链接。

帮助是非常感激的。:)

问题可能是因为您发送的每个请求都是index.html,即使浏览器通过

请求您的bundle.jsstyle.css
app.get('*', function (request, response){
  response.sendFile(path.join(__dirname + "/public/index.html"))
});

定义一个public文件夹,从这里可以提供这些文件,比如公共(在您的github repo中有您的index.html)。让webpack在该文件夹中生成bundle.js。还要指出你的index.html使用bundle.js从该文件夹。

接下来在你的server.js你需要做一些改变。让express在浏览器请求时使用公共路径来提供这些文件。

例如-

const app             = express();
const publicPath     = express.static(path.join(__dirname, 'public'), { redirect : false });
const indexPath  = path.join(__dirname, 'public/index.html');
app.use(publicPath);
app.get('/', function (_, res) { res.sendFile(indexPath) });
app.get('*', function (_, res) { res.sendFile(indexPath) });

首先你没有用你的webpack构建bundle.js文件。在你提供服务之前,你需要先构建它。

更改您的包。Json脚本到

"scripts": {
    "build": "webpack --progress --color --config  webpack.config.js --watch",
    "start": "node server.js"
  }

并在运行服务器之前运行命令npm run build

如果你的webpack bundle.js没有在/public/build目录下创建,那么在public目录下创建一个目录build,然后再运行上面的命令。