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

更新Dog Profile时触发Axios 404错误,求排查方案(附代码)

解决狗狗资料更新时的404错误

错误详情

更新Dog Profile时触发以下404请求错误:

PUT http://localhost:8080/dog-profile/dogprofile 404 (Not Found)
dogprofile.js:57 Error updating dog profile: AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', ...}

排查与解决步骤

1. 确认后端主服务已挂载总路由

检查你的后端入口文件(如app.js/server.js),确保已引入并使用总路由配置:

const routes = require('./routes/routes');
app.use('/', routes); // 必须存在这行代码,否则所有路由无法生效

如果缺少此配置,后端无法识别任何自定义路由,直接返回404。

2. 验证前端API的BaseURL配置

打开../services/api.js,确认BaseURL设置正确且以斜杠结尾:

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8080/', // 结尾必须带斜杠,否则路径拼接会出错
});

export default api;

若BaseURL未带斜杠,前端请求路径会变成http://localhost:8080/dog-profiledogprofile,导致路径无效。

3. 检查路由大小写与拼写一致性

虽然当前代码路径均为小写,但在区分大小写的系统(如Linux)中,需确保请求路径与后端路由完全匹配:

  • 前端请求路径:/dog-profile/dogprofile
  • 后端路由组合:routes.js中/dog-profile + dogProfileRoutes.js中/dogprofile
    若存在拼写错误(如DogProfile写成dogProfile),会直接导致路由不匹配。

4. 确认authMiddleware未拦截正常请求

检查authMiddleware.js逻辑,确保验证通过后调用next()传递请求:

const jwt = require('jsonwebtoken');

const authMiddleware = (req, res, next) => {
  const token = req.header('x-auth-token');
  if (!token) {
    return res.status(401).json({ msg: 'No token, authorization denied' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next(); // 必须调用next(),否则请求会被中断
  } catch (err) {
    res.status(401).json({ msg: 'Token is not valid' });
  }
};

module.exports = authMiddleware;

若中间件未调用next(),请求会被挂起,最终返回404。

5. 重启后端服务器

修改路由或中间件后,必须重启后端服务器才能加载新配置。未重启的话,服务器仍使用旧路由规则,导致请求无法匹配。

6. 直接测试后端路由

用Postman或curl直接测试后端接口,排除前端问题:

curl -X PUT http://localhost:8080/dog-profile/dogprofile \
  -H "x-auth-token: 你的授权Token" \
  -H "Content-Type: application/json" \
  -d '{"name":"Buddy","breed":"Labrador","age":3,"weight":25,"aggressionStatus":"calm","lastVisitDate":"2024-01-01"}'

若该请求也返回404,问题出在后端路由配置;若返回正常,则需排查前端请求的Token或数据格式问题。


附:你的代码参考

前端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 {
    const updatedDogProfile = await DogProfile.findOneAndUpdate(
      { owner: req.user.userId },
      req.body,
      { new: true }
    );
    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,
};

后端models/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;

后端routes/dogProfileRoutes.js

const express = require("express");
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/routes.js

const express = require('express');
const authRoutes = require('./authRoutes');
const appointmentRoutes = require('./appointmentRoutes');
const customerRoutes = require('./customerRoutes');
const aboutRoute = require('./aboutRoute');
const servicesRoute = require('./servicesRoute');
const contactsRoute = require('./contactsRoute');
const homeRoute = require('./homeRoute');
const dogProfileRoutes = require('./dogProfileRoutes');

const router = express.Router();

router.use('/auth', authRoutes);
router.use('/appointments', appointmentRoutes);
router.use('/customers', customerRoutes);
router.use('/dog-profile', dogProfileRoutes);
router.use('/about', aboutRoute);
router.use('/services', servicesRoute);
router.use('/contacts', contactsRoute);
router.use('/', homeRoute);

module.exports = router;

内容的提问来源于stack exchange,提问作者Sufiyan Mustafa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:00:56