【发布时间】:2019-11-29 05:14:33
【问题描述】:
使用 Node.js、Express、Socket.io、firebase admin+auth 和 Handlebars。
我收到错误Uncaught SyntaxError: Unexpected token <
当我使用res.redirect('/login'); 但当我删除res.redirect 时它会出现尝试包括重定向类型(301)将路径更改为../login /../login 但仍然有错误?
真的很难过这一点,任何帮助都会很棒!
似乎大多数其他关于它的讨论都停留在路径问题?
进口
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
var exphbs = require('express-handlebars');
我认为相关的代码
// Express and Handlebars
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
主要问题代码
// 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...
是express.static造成的吗?
app.use(express.static('/public'));
const port = 3000;
http.listen(port, () => console.log(`Example app listening on port ${port}!`))
login.handlebars
{{#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>
【问题讨论】:
-
错误发生在哪里?是服务器端还是客户端?无论哪种方式,请将登录模板添加到您的问题中,因为这可能就是问题所在。
-
在您初始化车把时,
hbs.engine未定义。再次尝试使用app.engine('handlebars', exphbs());,建议使用 path 来连接文件路径。 -
@jfriend00 导致它的代码是服务器端的,但错误在控制台中显示客户端,而且我从来没有这么快得到回复,并且在 3 小时后刚刚休息。加了模板,我觉得不是这样
-
然后,您的浏览器 Javascript 解释器在生成的 HTML 中出现错误。可能您将 HTML 与您的 Javascript 混合在一起。除非您向我们展示登录模板文件以及生成的 HTML(来自浏览器中的视图/源代码),否则我们无法为您提供更多帮助。
-
@jfriend00 已添加该模板
标签: javascript node.js express path middleware