You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 onSubmit handler to pass the event and call preventDefault() directly:
    <Form onSubmit={(e) => {
      e.preventDefault(); // Stop the browser from reloading the page
      updateProject();
    }} className="m-3 p-5">
    
  • Option 2: Update the updateProject function 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 projectCode has a valid value when making the PUT request. If it's empty or undefined, your API URL becomes http://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/yourproject if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:38:10