gpt4 book ai didi

javascript - Node.js 页面重定向 AJAX 登录?重定向后使用函数调用?

转载 作者:行者123 更新时间:2023-11-30 12:41:21 26 4
gpt4 key购买 nike

“/stories”页面是特定于用户的,需要有效的登录凭据。

在重定向之前, Node 、服务器端和正确记录验证,但不会重定向到故事页面..

这似乎是因为“You can't make a redirection after an AJAX. You need to do it yourself in Javascript”,但是这个问题的第一个答案中的代码似乎有些不完整..对于成功调用..

另外,如何在重定向后成功调用后续函数(refreshStories)?

这是 AJAX:

if (loginUsername.length != 0) {
console.log('there is a login: ' + loginUsername);
// make an ajax call
$.ajax({
dataType: 'json',
data: AjaxLoginData,
type: 'post',
url:"http://localhost:4200/api/v1/users",
success: (data, textStatus, jqXHR) ->
if typeof data.redirect == 'string'
window.location = data.redirect
success: refreshStories,
error: foundError
});

Node.js + Express4

router.route('/users')

// log in a user (accessed at POST http://localhost:4200/api/v1/users)
.post(function(req, res) {

var username = req.body.loginUsername;
var password = req.body.loginPassword;

authenticateUser(username, password, function(err, user){
console.log('authenticate user..');
if (user) {
console.log('yes user');
// subsequent requests will know the user is logged in
req.session.username = user.username;
console.log('set session username to: ' + req.session.username);

// res.redirect('/stories');
res.send({redirect: '/stories'});
console.log('user logged in .. redirect to stories');

} else {
console.log('user authentication badCredentials error..');
res.render('index', {badCredentials: true});
}
});
});

最佳答案

试试这个

if (loginUsername.length != 0) {
console.log('there is a login: ' + loginUsername);
// make an ajax call
$.ajax({
dataType: 'json',
data: AjaxLoginData,
type: 'post',
url:"http://localhost:4200/api/v1/users",
success: (data, textStatus, jqXHR) ->
if (typeof data.redirect == 'string')
window.location.replace(window.location.protocol + "//" + window.location.host + data.redirect);
error: foundError
});

window.location.replace(...) will best simulate an HTTP redirect How to redirect to another webpage in JavaScript/jQuery?

对于“refreshStories”内容,您应该在转到“/stories”时刷新故事

关于javascript - Node.js 页面重定向 AJAX 登录?重定向后使用函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24358564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com