404 在 Node Js 中执行创建操作时的消息

问题描述 投票:0回答:1

这是上面有表格的页面

import { React, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

import CourseList from '../components/CourseList';

function CoursesPage({ setCourse }) {
    // Use the Navigate for redirection
    const redirect = useNavigate();

    // Use state to bring in the data
    const [courses, setCourses] = useState([]);

    // RETRIEVE the entire list of Courses
    const loadCourses = async () => {
        const response = await fetch('/MongoCourses');
        const courses = await response.json();
        setCourses(courses);
    } 
    

    // UPDATE a single Course
    const onEditCourses = async course => {
        setCourse(course);
        redirect("/update");
    }


    // DELETE a single Courses  
    const onDeleteCourse = async _id => {
        const response = await fetch(`/MongoCourses/${_id}`, { method: 'DELETE' });
        if (response.status === 204) {
            const getResponse = await fetch('/MongoCourses');
            const courses = await getResponse.json();
            setCourses(courses);
        } else {
            console.error(`Unable to delete course. Error message = ${_id}, status code = ${response.status}`)
        }
    }

    // LOAD all the Courses
    useEffect(() => {
        loadCourses();
    }, []);

    // DISPLAY the Courses
    return (
        <>
            <h2>List of Courses</h2>
            <p>This is an ongoing list of courses I've taken for my Computer Science Degree.</p>
            <CourseList 
                courses={courses}
                onEdit={onEditCourses} 
                onDelete={onDeleteCourse} 
            />
        </>
    );
}

export default CoursesPage;

这是添加表格页面

从 'react' 导入 React, { useState }; 从“react-router-dom”导入{useNavigate};

//更改图标、功能名称、参数 // 适合您的投资组合主题和架构。

导出常量 AddCoursePageForm = () => {

const [courseNumber, setNumber]     = useState('');
const [courseName, setName]         = useState('');
const [description, setDescription] = useState('');
const [courseDate, setDate]         = useState('');;


const redirect = useNavigate();

const addCourse = async () => {
    const newCourse = {courseNumber, courseName, description, courseDate };
    const response = await fetch('/MongoCourses', {
        method: 'post',
        body: JSON.stringify(newCourse),
        headers: {
            'Content-Type': 'application/json',
        },
    });
    if(response.status === 201){
        alert(`Successfully added ${courseName}`);
        redirect("/coursesPage");
    } else {
        alert(`Unable to add course. Please check all fields are filled out correctly. Error message =  ${response.status}`);
        redirect("/coursesPage");
    }
};


return (
    <>
    <article>
        <h2>Add a Course</h2>
        <p>Paragraph about this page.</p>
        <form onSubmit={(e) => { e.preventDefault();}}>
            <fieldset>
                <legend>What course are you adding?</legend>
                <label for="courseNumber">Course Number</label>
                <input
                    type="text"
                    placeholder="CS 101"
                    value={courseNumber}
                    onChange={e => setNumber(e.target.value)} 
                    id="courseNumber" 
                    required/>
                
                <label for="courseName">Course Name</label>
                <input
                    type="text"
                    value={courseName}
                    placeholder="Intro to Computer Science"
                    onChange={e => setName(e.target.value)} 
                    id="courseName" 
                    required/>

                <label for="description">Course Description</label>
                <textarea 
                    type="text"
                    placeholder="Course Description (500 characters or less)"
                    value={description}
                    onChange={e => setDescription(e.target.value)} 
                    id="description" 
                    maxlength="500" 
                    ></textarea>

                <label for="courseDate">Date Completed</label>
                <input
                    type="date"
                    placeholder="Date Completed"
                    value={courseDate}
                    onChange={e => setDate(e.target.value)} 
                    id="courseDate" />                
                    

                <label for="submit">
                <button
                    type="submit"
                    onClick={addCourse}
                    id="submit"
                >Add</button></label>
            </fieldset>
            </form>
        </article>
    </>
);

}

导出默认的AddCoursePageForm;

我几周前就开始工作了,但我不知道我搞砸的地方。

html node.js post
1个回答
0
投票

您需要在“fetch”函数中指定主机。假设您的 React 应用程序在 localhost:3000 上运行,当您发出这样的 fetch 请求时,它会尝试调用 localhost:3000/MongoCourses,这是一个无效的 URL。这就是它返回 404 错误代码的原因。

const response = await fetch('http://<backend_url>/MongoCourses');
© www.soinside.com 2019 - 2024. All rights reserved.