使用 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}!`))
登录.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>
最佳答案
该错误是由 res.redirect('/login');
重定向 public 文件夹中的脚本引起的,因此脚本 src js/client.js
将被重定向到/login
。
这是因为中间件 app.use(function(req, 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');
}
关于javascript - 表达 res.redirect 导致 "Uncaught SyntaxError: Unexpected token <",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125503/