2016-08-12 59 views
0

我正在使用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); 

回答

0

嗯...我希望我有一個更好的答案,但是我只是很高興我得到了它的工作。我以靜態方式提供文件的方式將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'); 
    } 

});