POST请求提交用户输入出现403错误求助(Express+Passport)
Hey there! Let's work through why you're hitting that 403 error and request timeout on your signup endpoint. I’ve looked over your code, and there are a couple of critical fixes needed:
1. 核心问题:Passport认证逻辑未正确执行
In your POST route, after passing express-validator checks, you’re defining the passport.authenticate middleware but never actually running it. This leaves the request hanging indefinitely (causing the timeout) and means Passport’s authentication flow never triggers—likely contributing to the 403 error too.
Here’s the fixed route code:
router.post("/user/signup", [ check('email', 'Your email is not valid').not().isEmpty().isEmail().normalizeEmail(), check('password', 'Your password must be at least 5 characters').not().isEmpty().isLength({min: 5}) ], function (req, res, next) { const errors = validationResult(req); console.log(req.body); if (!errors.isEmpty()) { return res.status(422).jsonp(errors.array()); } else { // 关键:手动调用Passport中间件,传入req/res/next passport.authenticate("local.signup", { successRedirect: "/user/profile", failureRedirect: "/user/signup", failureFlash: true })(req, res, next); } });
passport.authenticate() returns a middleware function—you need to invoke it with the request, response, and next parameters to make it process the authentication flow. Your original code only created the middleware but didn’t execute it, leaving the request unhandled.
2. 检查CSRF保护(常见403触发原因)
If your Express app uses the csurf middleware, AJAX requests must include a CSRF token to pass validation (otherwise you’ll get a 403). Fix this with:
- Add a hidden CSRF token field to your signup page:
<input type="hidden" name="_csrf" value="<%= csrfToken %>"> - Include the token in your AJAX data:
$.ajax({ url: '/user/signup', type: 'POST', cache: false, data: { email: $('#email').val(), password: $('#password').val(), _csrf: $('input[name="_csrf"]').val() // 带上CSRF token }, // 原有success/error逻辑不变 });
3. 前端错误处理的小修复
In your error callback, you’re using vanilla JS innerHTML on a jQuery object—switch to jQuery’s .html() method instead:
// 替换 errorsContainer.innerHTML = ''; errorsContainer.html('');
Finally, double-check that your local.signup Passport strategy is properly implemented (it should handle creating the user record without internal errors that could hang the request).
After these tweaks, your signup request should process normally without 403 errors or timeouts.
内容的提问来源于stack exchange,提问作者Jerry 132

