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

ReactJS中根据slug获取数据遇Axios 404错误,求排查

问题分析与修复方案

核心错误点

  • 请求地址完全错误:你实际要调用的API是https://bulkaccounts.com/api/blogs,但代码里axios请求的是http://localhost:3000/blog/${slug},本地服务根本没有这个接口,直接触发404。
  • 数据渲染逻辑混乱:你把API地址的字符串变量data当成返回数据去遍历data.datas.data,这完全不成立——字符串没有datas属性,应该用请求回来的状态数据渲染。
  • 未匹配API的查询规则:你需要先确认目标API支持哪种单篇博客查询方式,是路径参数(比如/api/blogs/${slug})还是查询参数(比如/api/blogs?slug=${slug})。

修复后的完整代码

import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";

// 正确的API基础地址
const API_BASE_URL = "https://bulkaccounts.com/api/blogs";

function Singleblog() {
  const { slug } = useParams();
  const [blog, setBlog] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchBlogBySlug = async () => {
      setIsLoading(true);
      setError(null);

      try {
        // 先调用基础API拿到所有博客,再筛选对应slug的内容
        // 如果API支持直接通过slug查询,可改成`${API_BASE_URL}/${slug}`或`${API_BASE_URL}?slug=${slug}`
        const res = await axios.get(API_BASE_URL);
        const targetBlog = res.data?.find(item => item.slug === slug);
        
        if (targetBlog) {
          setBlog(targetBlog);
        } else {
          setError("未找到该博客");
        }
      } catch (error) {
        console.error("请求失败:", error);
        setError("获取博客内容失败,请稍后重试");
      }

      setIsLoading(false);
    };

    // 确保slug存在时再发起请求
    if (slug) fetchBlogBySlug();
  }, [slug]);

  // 状态分支处理
  if (isLoading) return <div>加载中...</div>;
  if (error) return <div className="error">{error}</div>;
  if (!blog) return <div>未找到对应博客</div>;

  // 渲染实际博客内容
  return (
    <>
      <div className="blog">
        <div className="flex-container">
          <div className="card">
            <h1>{blog.title}</h1>
            <div dangerouslySetInnerHTML={{ __html: blog.content }} />
          </div>
        </div>
      </div>
      <Link to="/">返回首页</Link>
    </>
  );
}

export default Singleblog;

额外注意事项

  1. 先确认API结构:先手动调用https://bulkaccounts.com/api/blogs查看返回数据格式,确认单篇博客的查询方式,再调整axios请求地址,避免瞎猜。
  2. 状态逻辑简化:移除了无用的items状态,增加了加载、错误、空数据的状态提示,提升用户体验。
  3. 渲染逻辑修正:直接用请求到的blog状态渲染内容,不再对字符串变量做无效遍历。

内容的提问来源于stack exchange,提问作者Bittu Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:35:32