后端重定向后页面未刷新求助:Web应用注册POST请求页面跳转异常
Hey there, let's break down why your redirect isn't working even though the backend sends a /login redirect response.
The Root Cause
When you send the signup request using AJAX/fetch/axios (modern frontend JS methods), the browser's XMLHttpRequest API automatically follows the redirect under the hood—but it only retrieves the response content from the redirected path. It won't trigger a full page reload or navigation. This is intentional behavior for asynchronous requests, since they're designed to update parts of the page without refreshing.
Solution 1: Return a JSON Response & Handle Redirect on the Frontend
Instead of sending a redirect from the backend, send a JSON object with the target URL, then let the frontend handle the page navigation.
First, fix your backend code (note: also corrected the error handling to use your CustomAPIError properly):
const CustomAPIError = require('../../errors/customError') const jwt = require('jsonwebtoken') require('dotenv').config() const login = async (req, res) => { res.status(200).json({ msg: 'logged in' }) } const createsignupuser = async (req, res) => { const { Firstname, Lastname, Email, password, confirmPassword, username } = req.body if (!Firstname || !Lastname || !Email || !password || !confirmPassword || !username) { throw new CustomAPIError("please provide appropriate credentials", 400) } if (password !== confirmPassword) { throw new CustomAPIError('password does not match', 400) } // Return JSON with redirect instruction instead of redirect response return res.status(200).json({ redirectUrl: '/login' }) } module.exports = { createsignupuser, login }
Then update your frontend code to handle the redirect. For example, if you're using fetch:
// Assuming you have form data collected in a variable called formData fetch('/your-signup-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }) .then(response => response.json()) .then(data => { // Trigger page navigation to the login route window.location.href = data.redirectUrl; }) .catch(error => { console.error('Signup error:', error); // Handle error messages here (e.g., show to user) });
Solution 2: Use Traditional Form Submission (No AJAX)
If you're using a plain HTML form instead of AJAX, make sure you're not preventing the default form submission behavior.
Check your frontend code for any event.preventDefault() in the form's submit handler. For example:
<form id="signupForm" action="/your-signup-endpoint" method="POST"> <!-- Your form fields here --> <button type="submit">Sign Up</button> </form> <script> // If you have this, remove it (or adjust to let the default submission happen) document.getElementById('signupForm').addEventListener('submit', (e) => { e.preventDefault(); // This blocks the browser's default form submission // ... your AJAX code }); </script>
If you remove e.preventDefault(), the browser will handle the form submission natively, and the backend's redirect response will trigger a page jump to /login as expected.
Quick Note on Error Handling
I noticed you were throwing a generic Error instead of your CustomAPIError in some cases. Make sure to use CustomAPIError consistently so your error middleware can properly handle status codes and responses.
内容的提问来源于stack exchange,提问作者penguinz0

