我尝试运行我的前端和服务器端应用程序,但当我尝试更新我的狗配置文件时,我收到此错误
PUT http://localhost:8080/dog-profile/dogprofile 404 (Not Found)
dispatchXhrRequest @ xhr.js:272
xhr @ xhr.js:63
dispatchRequest @ dispatchRequest.js:61
_request @ Axios.js:179
request @ Axios.js:49
httpMethod @ Axios.js:218
wrap @ bind.js:9
onSubmit @ dogprofile.js:46
eval @ index.esm.mjs:2214
await in eval (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
eval @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26135
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 23 more frames
Show less
dogprofile.js:57 Error updating dog profile: AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}code: "ERR_BAD_REQUEST"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Request failed with status code 404"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: {…}, status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}stack: "AxiosError: Request failed with status code 404\n at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:125:66)\n at Axios.request (webpack-internal:///./node_modules/axios/lib/core/Axios.js:54:41)\n at async onSubmit (webpack-internal:///./pages/dogprofile.js:55:30)\n at async eval (webpack-internal:///./node_modules/react-hook-form/dist/index.esm.mjs:2214:13)"[[Prototype]]: Error
我已经在这件事上坚持了几个小时了,我不知道该做什么。 这就是我前端的dogprofile.js
import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { Form, Button } from 'react-bootstrap';
import api from '../services/api';
import { toast } from 'react-toastify';
const DogProfile = () => {
const { register, handleSubmit, setValue } = useForm();
const [dogProfile, setDogProfile] = useState({
name: '',
breed: '',
age: '',
weight: '',
aggressionStatus: '',
lastVisitDate: ''
});
const [user, setUser] = useState(null);
useEffect(() => {
setUser(JSON.parse(localStorage.getItem('userLoggedIn')));
}, []);
useEffect(() => {
const fetchDogProfile = async () => {
try {
const token = localStorage.getItem('authToken');
const response = await api.get('/dog-profile/dogprofile', {
headers: {
'x-auth-token': token
}
});
setDogProfile(response.data);
} catch (error) {
console.error('Error fetching dog profile:', error);
}
};
if (user) {
fetchDogProfile();
}
}, [user]);
const onSubmit = async (data) => {
try {
const token = localStorage.getItem('authToken');
const response = await api.put('/dog-profile/dogprofile', data, {
headers: {
'x-auth-token': token
}
});
console.log(response);
toast.success('Dog profile updated successfully', {
autoClose: 1000,
position: "bottom-center"
});
} catch (error) {
console.error('Error updating dog profile:', error);
toast.error('Failed to update dog profile');
}
};
return (
<>
<h1 className='my-3'>Dog Profile</h1>
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Group controlId="name">
<Form.Label>Name</Form.Label>
<Form.Control defaultValue={dogProfile.name} {...register('name')} />
</Form.Group>
<Form.Group controlId="breed">
<Form.Label>Breed</Form.Label>
<Form.Control defaultValue={dogProfile.breed} {...register('breed')} />
</Form.Group>
<Form.Group controlId="age">
<Form.Label>Age</Form.Label>
<Form.Control defaultValue={dogProfile.age} {...register('age')} />
</Form.Group>
<Form.Group controlId="weight">
<Form.Label>Weight</Form.Label>
<Form.Control defaultValue={dogProfile.weight} {...register('weight')} />
</Form.Group>
<Form.Group controlId="aggressionStatus">
<Form.Label>Aggression Status</Form.Label>
<Form.Control defaultValue={dogProfile.aggressionStatus} {...register('aggressionStatus')} />
</Form.Group>
<Form.Group controlId="lastVisitDate">
<Form.Label>Last Visit Date</Form.Label>
<Form.Control type="date" defaultValue={dogProfile.lastVisitDate} {...register('lastVisitDate')} />
</Form.Group>
<Button variant="primary" type="submit">
Save Changes
</Button>
</Form>
</>
);
};
export default DogProfile;
这些是我的服务器端文件
dogProfileController.js
const DogProfile = require("../models/dogProfile");
const getDogProfile = async (req, res) => {
try {
const dogProfile = await DogProfile.findOne({ owner: req.user.userId });
if (!dogProfile) {
return res.status(404).json({ msg: "Dog profile not found" });
}
res.json(dogProfile);
} catch (error) {
console.error("Error fetching dog profile:", error);
res.status(500).send("Internal Server Error");
}
};
const updateDogProfile = async (req, res) => {
try {
// Logic for updating dog profile based on the user's ID from req.user
const updatedDogProfile = await DogProfile.findOneAndUpdate(
{ owner: req.user.userId }, // Filter by owner ID
req.body, // Update with request body
{ new: true } // Return the updated document
);
if (!updatedDogProfile) {
return res.status(404).json({ msg: "Dog profile not found" });
}
console.log("Updated Dog Profile:", updatedDogProfile);
res.json(updatedDogProfile);
console.log("Dog profile updated successfully");
} catch (error) {
console.error("Error updating dog profile:", error);
res.status(500).send("Internal Server Error");
}
};
module.exports = {
getDogProfile,
updateDogProfile,
};
模型/dogProfile.js
const mongoose = require("mongoose");
const dogProfileSchema = new mongoose.Schema({
owner: { type: mongoose.Schema.Types.ObjectId, ref: "Customer", required: true },
name: { type: String, required: true },
breed: { type: String, required: true },
age: { type: Number, required: true },
weight: { type: Number, required: true },
aggressionStatus: { type: String, required: true },
lastVisitDate: { type: Date, required: true },
});
const DogProfile = mongoose.model("DogProfile", dogProfileSchema);
module.exports = DogProfile;
路线/dogProfileRoutes.js
// routes/dogProfileRoutes.js
const express = require("express");
const Dog = require("../models/dogProfile");
const dogProfileController = require("../controllers/dogProfileController");
const authMiddleware = require("../middleware/authMiddleware");
const router = express.Router();
router.use(authMiddleware);
router.get("/dogprofile", dogProfileController.getDogProfile);
router.put("/dogprofile", dogProfileController.updateDogProfile);
module.exports = router;
routes.js // 路线/routes.js
const express = require('express');
const authRoutes = require('./authRoutes');
const appointmentRoutes = require('./appointmentRoutes');
const customerRoutes = require('./customerRoutes');
const aboutRoute = require('./aboutRoute'); // Import the aboutRoute module
const servicesRoute = require('./servicesRoute'); // Import the servicesRoute module
const contactsRoute = require('./contactsRoute'); // Import the contactsRoute module
const homeRoute = require('./homeRoute'); // Import the homeRoute module
const dogProfileRoutes = require('./dogProfileRoutes'); // Import the dogProfileRoutes module
const router = express.Router();
// Delegate specific functionalities to separate route files
router.use('/auth', authRoutes);
router.use('/appointments', appointmentRoutes);
router.use('/customers', customerRoutes);
router.use('/dog-profile', dogProfileRoutes);
// Include the about route
router.use('/about', aboutRoute);
router.use('/services', servicesRoute); // Include the services route
// Include the contacts route
router.use('/contacts', contactsRoute);
// Include the home route
router.use('/', homeRoute);
module.exports = router;
我不知道这是否有帮助,但也许在匹配“响应”中的前端路由时存在问题。
const response = await api.get('/dog-profile/dogprofile', {
headers: {
'x-auth-token': token
}
尝试删除/dog-profile