React+Node+MySQL项目中表单编辑后出现404错误且自动登出的问题求助
Hey there, let's break down what's going on here and fix those issues step by step!
1. Fix the Page Refresh & Logout Issue
The main culprit here is the default form submission behavior—when you click the submit button, the browser triggers a full page reload. This wipes out all React state (including your userId and authentication context values), which is why you get logged out immediately after submitting.
To fix this, you need to prevent the default form submission action:
- Option 1: Modify the form's
onSubmithandler to pass the event and callpreventDefault()directly:<Form onSubmit={(e) => { e.preventDefault(); // Stop the browser from reloading the page updateProject(); }} className="m-3 p-5"> - Option 2: Update the
updateProjectfunction to accept the event and handle the prevention there:const updateProject = (e) => { e.preventDefault(); // Add this line first to block page reload Axios.put(`http://localhost:3001/lecteditproject/${projectCode}`,{ projectId: projectCode, projectTitle: projectTitle, projectInformation: projectInformation, collaboratorId: collaboratorId, }).then((response) => { if(response){ window.alert('Your project has been updated!'); history.push(`/lecturer/${userId}/yourproject`); } else{ window.alert('Update is unsuccessful!'); } }) } // Then keep the form's onSubmit as is: <Form onSubmit={updateProject} className="m-3 p-5">
This will stop the page from reloading, so your React context state (like userId) stays intact, and you won't be logged out anymore.
2. Troubleshoot the 404 Error
The 404 is almost certainly a side effect of the page refresh—when the browser reloads, it tries to request the current page's URL, which might not exist in your server's routing setup. Once you fix the page refresh, this error should disappear. But let's double-check a couple of edge cases:
- Ensure
projectCodehas a valid value when making the PUT request. If it's empty or undefined, your API URL becomeshttp://localhost:3001/lecteditproject/, which would return a 404. Since you said the data updates successfully, this is probably not the issue, but you can add a quick check to be safe:const updateProject = (e) => { e.preventDefault(); if(!projectCode) { window.alert("Project code is required to update!"); return; } // ... rest of your Axios code } - Verify your React Router routes are set up correctly for
/lecturer/${userId}/yourproject—make sure there's a route defined that matches this pattern (using route params like/lecturer/:userId/yourprojectif needed).
3. Bonus: Improve Form Initialization
Right now, your form fields start with empty values. You probably want to load the existing project data when the component mounts so the user can edit the current details instead of starting from scratch. Add an useEffect to fetch the project information:
import { useParams } from 'react-router-dom'; // Add this import if you get projectCode from route params function LecturerEditProject(){ const { projectCode } = useParams(); // Get projectCode from your route (adjust if you pass it another way) // ... your existing state and context hooks useEffect(() => { // Fetch existing project data to populate the form Axios.get(`http://localhost:3001/project/${projectCode}`) .then(response => { const project = response.data[0]; // Adjust based on your API's response structure setProjectTitle(project.project_title); setProjectInformation(project.project_information); setCollaboratorId(project.representative_id); }) .catch(err => console.log("Failed to load project data:", err)); }, [projectCode]); // ... rest of your component code }
Final Notes
After implementing the first fix (preventing default form submission), your history.push should work smoothly without page reloads, and you won't be logged out anymore. The 404 error should vanish once the page stops refreshing.
内容的提问来源于stack exchange,提问作者red17

