Express.js,意外令牌 < [英] Express.js, Unexpected token <

查看:16
本文介绍了Express.js,意外令牌 <的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的快速服务器,看起来像这样:

I have simple express server which looks like that:

Epxpress 应用程序:

var express = require('express');
var compression = require('compression');
var path = require('path');
var cors = require('cors');
var router = express.Router();

var app = express();

app.use('/bundle', express.static(path.join(__dirname, '/bundle')));

app.enable('trust proxy');

app.use(compression());

app.get('*', function(req, res) {
    res.header('Cache-Control', "max-age=60, must-revalidate, private");
    res.sendFile( path.join(__dirname, 'index.html') );
});


var server = app.listen(process.env.PORT || 5000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log(`Example app listening at http://%s:%s`, host, port);
});

和简单的html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Router test</title>
</head>
<body>
    <div id="root"></div>
    <script src="bundle.js"></script>
</body>
</html>

在 bundle.js 中,我有带有客户端路由的 ReactJS 应用程序:

Inside of bundle.js i have ReactJS application with client-side routing:

render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <Route path="about" component={About} />
            <Route path="about2" component={About2} />
            <Route path="about3" component={About3} />
            <Route path="*" component={NoMatch} />
        </Route>
        <Route path="*" component={NoMatch} />
    </Router>
), document.getElementById('root'));

每当我尝试导航到 domain:port/(路由器支持此路由)时,一切都很好.但是当我尝试导航到更复杂的 URL 时,例如 domain:port///.. 等,我在浏览器中出现错误:

Whenever i try to navigate to domain:port/ (this route is supported by router) everething is OK. But when i try to navigate to more complex URL, like domain:port///.. etc i got an error in browser:

bundle.js:1 Uncaught SyntaxError: Unexpected token <

看起来不是从带有 index.html 的静态服务器响应发送 bundle.js 并且在 bundle.js 内部有 html 标记.

looke like instead of send bundle.js from static server response with index.html and inside bundle.js there is html markup.

我该如何解决这个问题?

How can i fix this?

谢谢!

推荐答案

似乎发生了环回,因为 * 规则为 index.html 每时间,当找不到 bundle.js 时,它会改为提供 index.html,从而尝试将 < 解析为 javascript.

There seems to be a loopback occuring, since the * rule is serving a index.html every time, and when bundle.js is not found, it will serve index.html instead, thus trying to parse < as javascript.

一种index-ception,如果你愿意......

A sort of index-ception if you will...

这篇关于Express.js,意外令牌 &lt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆