Javascript Express res.重定向导致“未捕获的语法错误:意外标记
使用Node.js、Express、Socket.io、firebase admin+auth和handlebarJavascript Express res.重定向导致“未捕获的语法错误:意外标记,javascript,node.js,express,path,middleware,Javascript,Node.js,Express,Path,Middleware,使用Node.js、Express、Socket.io、firebase admin+auth和handlebar 我得到了错误Uncaught SyntaxError:Unexpected token错误是由res.redirect'/login'引起的;正在重定向公用文件夹中的脚本,因此脚本src js/client.js将被重定向到/login 这是因为中间件app.usefunctionreq、res、next会在所有HTTP请求上触发 修复程序将其改为在路由上使用函数: 例如: app
我得到了错误Uncaught SyntaxError:Unexpected token错误是由res.redirect'/login'引起的;正在重定向公用文件夹中的脚本,因此脚本src js/client.js将被重定向到/login 这是因为中间件app.usefunctionreq、res、next会在所有HTTP请求上触发 修复程序将其改为在路由上使用函数: 例如:
app.get('/', isAuthenticated, (req, res) => {
res.render('home', {
showTitle: true,
title: 'Home'
});
});
功能:
function isAuthenticated(req, res, next) {
if (uid)
return next();
// IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM
res.redirect('/login');
}
错误发生在哪里?它是服务器端还是客户端?无论哪种方式,请将登录模板添加到您的问题中,因为这可能就是问题所在。在您初始化handlebar时,未定义hbs.engine。尝试使用app.engine'handlebars',exphbs;同样,建议使用path连接文件路径。@jfriend00导致此错误的代码是服务器端的,但错误显示在控制台中的客户端,而且我从来没有这么快收到回复,在3小时后刚刚休息。在添加了模板之后,我不认为是这样,您在生成的HTML中出现了一个错误,您的浏览器Javascript解释器被这个错误绊倒了。可能您的Javascript中混入了HTML。除非您在浏览器中向我们显示登录模板文件以及从View/Source生成的HTML,否则我们无法进一步帮助您。@jfriend00已添加该模板
// show login page before middleware check (works fine)
app.get('/login', (req, res) => {
res.render('login', {
showTitle: true,
title: 'Login'
});
});
// Auth Check All Pages HERE Catches access to all other pages
// Main Issue
app.use(function(req, res, next) {
console.log('[firebase.auth()] ', firebase.auth().currentUser);
if(firebase.auth().currentUser === null){
res.redirect('/login');
return; // same problem without return
}else{
next();
}
});
// all other routes...
app.use(express.static('/public'));
const port = 3000;
http.listen(port, () => console.log(`Example app listening on port ${port}!`))
{{#if showTitle}}
<h1>{{title}}</h1>
{{/if}}
<form id="login" >
<label for="email">Email Address</label>
<input id="email" type="email" value="ben@bnr.io"/>
<label for="pass">Password</label>
<input id="pass" type="password"/>
<button>Login</button>
</form>
app.get('/', isAuthenticated, (req, res) => {
res.render('home', {
showTitle: true,
title: 'Home'
});
});
function isAuthenticated(req, res, next) {
if (uid)
return next();
// IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM
res.redirect('/login');
}