具有外部资源的快递和静态资产
问题描述:
我正在使用Express来提供静态资产。前端是AngularJS 1.x,我启用了html5mode。想实现的Recaptcha是我注意到,在Chrome浏览器开发工具如下:具有外部资源的快递和静态资产
Uncaught SyntaxError: Unexpected token <
api.js?onload=vcRecaptchaApiLoaded&render=explicit“:1
当我在功能上点击启动的ReCaptcha过程中,我得到:
Error: reCaptcha has not been loaded yet.
到目前为止,这是有道理的是因为我注意到第一个错误报告的字符串是从Google加载Recaptcha的url路径的一部分。
当我在铬工具中点击url(api.js?onload = vcRecaptchaApiLoaded & render = explicit“:1)时,它会加载我的index.html!奇怪!
这已被认为与我的静态资产服务有关。我已经玩过我的快递服务器,直到奶牛回家,并不知道如何补救。
活生生的例子: http://ninjacape.herokuapp.com
这里是我的代码,并感谢您考虑看看!
的index.html
<script src=“https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit“ async defer></script>
express.js
var express = require('express');
var compression = require('compression');
var app = module.exports.prod = exports.prod = express();
var devAPI = 'http://localhost:1337';
app.use(compression());
app.use(express.static('.tmp'));
app.get('/*', function(req, res) {
res.sendFile(__dirname + '/.tmp/index.html');
});
var proxy = require('express-http-proxy');
app.use('/api', proxy(devAPI));
var port = process.env.PORT || 8000;
app.listen(port);
答
嗯...我希望我有一个更好的答案,但是我只是很高兴我得到了它的工作。我以静态方式提供文件的方式将index.html中的任何url附加到http://localhost:8000。为了解决这个问题,我查看了进入Express的实际请求并找到了url。然后添加逻辑将该请求重定向到真实的url。请参阅下面的注释代码以获取更多信息:
// Any requests matching /*
app.get('/*', function(req, res, next) {
// Log the original url express is tying to go to
console.log(req.url);
// This is the url found from the step above (Where are the extra characters coming from?!)
var url ='/%E2%80%9Chttps://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit%E2%80%9C'
// Self explanatory
if (req.url === url) {
// Respond by redirecting the request
res.redirect('https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit')
//End this block and continue
next();
} else {
// If it doesn't match the above url, proceed as normal
res.sendFile(__dirname + '/.tmp/index.html');
}
});