Javascript-форум (https://javascript.ru/forum/)
-   Node.JS (https://javascript.ru/forum/node-js-io-js/)
-   -   Функция next() (простой вопрос) (https://javascript.ru/forum/node-js-io-js/80431-funkciya-next-prostojj-vopros.html)

evgenomus 04.06.2020 11:28

Функция next() (простой вопрос)
 
Почему не работает переход по функции next()?
Браузер постоянно делает запросы, страница загружается, в терминале Node.js вижу 'checkAuth() is TRUE'. Но переход по адресу не происходит.

function checkAuth() {
	return app.use((req, res, next) => {
		if (req.user) {
			console.log('checkAuth() is TRUE');
			next();
		} else {
			console.log('checkAuth() is FALSE');
			res.redirect('/');
		}
	});
}

app.get('/home', checkAuth(), (req, res) => {
	res.sendFile(__dirname + "/private/home.html")
});


А вот такая конструкция работает:
function checkAuth() {
	return app.use((req, res, next) => {
		if (req.user) {
			console.log('checkAuth() is TRUE');
			//next();
			res.sendFile(__dirname + "/private/home.html");
		} else {
			console.log('checkAuth() is FALSE');
			res.redirect('/');
		}
	});
}

app.get('/home', checkAuth(), (req, res) => {
	//res.sendFile(__dirname + "/private/home.html")
});

SuperZen 05.06.2020 09:22

function checkAuth(req, res, next) {
		if (req.user) {
			console.log('checkAuth() is TRUE');
			next();
		} else {
			console.log('checkAuth() is FALSE');
			res.redirect('/');
		}
}

app.get('/home', checkAuth, (req, res) => {
	res.sendFile(__dirname + "/private/home.html")
});


app.use(...) - повесить глобальный middleware
app.get('/', () => здесь router specific middleware

)

evgenomus 05.06.2020 11:13

Цитата:

Сообщение от SuperZen (Сообщение 525462)
app.use(...) - повесить глобальный middleware
app.get('/', () => здесь router specific middleware

Спасибо. Работает!


Часовой пояс GMT +3, время: 01:47.