我正在使用react-router与浏览器历史记录。该功能:
app.get('*', function (request, response){
response.sendFile(path.join(__dirname + "/public/index.html"))
})
应该发送 Index.html,因为路由是通过 React-router 在客户端发生的。 但不知怎的,我的index.html被服务器误解了,我得到了这个错误:
未捕获的语法错误:意外的标记<
我不知道问题出在哪里。文件路径是否错误?我的树看起来像这样:
/app
/app/myJavascriptStuff.js
/public
/public/index.html
/moreStuffThatsNotRelevant
/server.js <- my express file
如果没有上述功能,我的页面通常会响应:
无法获取/无论什么
在 localhost:3000 上未发生的每个页面刷新(例如 localhost:3000/其他)
因为我知道我不擅长描述事物,here是存储库的链接。
非常感谢您的帮助。 :)
最佳答案
问题可能是因为对于每个请求,即使浏览器要求您提供 bundle.js
或 style.css
,您也会发送 index.html
通过
app.get('*', function (request, response){
response.sendFile(path.join(__dirname + "/public/index.html"))
});
定义一个 public
文件夹,可以在其中提供这些文件,比如说 public(您的 github 存储库中有 index.html
)。让 webpack 在该文件夹中生成 bundle.js
。另请指向您的 index.html
以使用该文件夹中的 bundle.js
。
接下来,您需要在 server.js
中进行一些更改。当浏览器询问时,让 express
使用公共(public)路径来提供这些文件。
一个例子可以是 -
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) });
关于javascript - Express'response.sendFile() 发送未捕获的语法错误 : Unexpected token <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404516/