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

GitHub Pages部署中questlist.txt路径404错误排查求助

React组件部署到GitHub Pages后无法获取questlist.txt(404错误)

问题情况

用React开发QuestCarousel组件,通过Jekyll部署到GitHub Pages后,请求questlist.txt一直返回404,浏览器显示的请求路径是/Quest/questlist.txt。已确认文件已复制到本地./dist目录,且工作流里的调试步骤显示文件位置正确,但问题仍未解决。

组件代码(QuestCarousel.tsx)

import React, { useState, useEffect } from "react";
import { Carousel } from "@mantine/carousel";
import { TextInput } from "@mantine/core";
import "./index.css";
import { NavLink } from "react-router-dom";

const QUEST_FILE_PATH = "/dist/Quests/questlist.txt";

const QuestCarousel: React.FC = () => {
  const [questList, setQuestList] = useState<string[]>([]);
  const [searchQuery, setSearchQuery] = useState<string>("");

  useEffect(() => {
    fetchQuestList();
  }, []);

  const fetchQuestList = async () => {
    try {
      const response = await fetch(`${QUEST_FILE_PATH}`);
      const text = await response.text();
      const quests = text.split(",");
      setQuestList(quests);
      console.log(quests);
    } catch (error) {
      console.error("Error fetching quest list:", error);
    }
  };

  const filteredQuests = questList.filter((quest) =>
    quest.toLowerCase().includes(searchQuery.toLowerCase())
  );
  
  function handleSearchChange(event: React.ChangeEvent<HTMLInputElement>) {
    setSearchQuery(event.target.value);
  }
  
  return (
    <>
      <div>
        <TextInput
          label="Search for Quest"
          placeholder="Type in a quest"
          size="md"
          value={searchQuery}
          onChange={handleSearchChange}
        />
      </div>

      <div className="carousel-container">
        <Carousel maw={320} mx="auto" withIndicators height={200}>
          {filteredQuests.map((quest, index) => {
            let questTEdit = quest.toLowerCase().split(" ");
            let pattern = /[!,`']/g;
            let modifiedQuestVal1 = questTEdit
              .join("")
              .replace(pattern, "");

            return (
              <Carousel.Slide key={index}>
                <NavLink
                  to="/QuestPage"
                  state={{
                    questName: quest,
                    modified: modifiedQuestVal1,
                  }}
                >
                  {quest}
                </NavLink>
              </Carousel.Slide>
            );
          })}
        </Carousel>
      </div>
    </>
  );
};

export default QuestCarousel;

已经尝试过的路径写法

  • /../dist/questlist.txt
  • /../../dist/questlist.txt
  • ./questlist.txt

Jekyll部署工作流配置

# Sample workflow for building and deploying a Jekyll site to GitHub Pages
name: Deploy Jekyll with GitHub Pages dependencies preinstalled

on:
    # Runs on pushes targeting the default branch
    push:
        branches: ["master"]

    # Allows you to run this workflow manually from the Actions tab
    workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
    contents: read
    pages: write
    id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
    group: "pages"
    cancel-in-progress: false

jobs:
    # Build job
    build:
        runs-on: ubuntu-latest
        steps:
            - name: Checkout
              uses: actions/checkout@v3

            # Debugging Step 1: List the contents of the directory
            - name: List Contents
              run: ls -R

            - name: Setup Pages
              uses: actions/configure-pages@v3

            # Debugging Step 3: Print environment variables
            - name: Print Environment Variables
              run: env

            - name: Build with Jekyll
              uses: actions/jekyll-build-pages@v1
              with:
                  source: ./dist
                  destination: ./_site

            # Debugging Step 4: Display the contents of the _site directory
            - name: Display _site Contents
              run: ls -R ./_site

            - name: Upload artifact
              uses: actions/upload-pages-artifact@v2

    # Deployment job
    deploy:
        environment:
            name: github-pages
            url: ${{ steps.deployment.outputs.page_url }}
        runs-on: ubuntu-latest
        needs: build
        steps:
            - name: Deploy to GitHub Pages
              id: deployment
              uses: actions/deploy-pages@v2

环境判断逻辑尝试(未解决)

const QUEST_FILE_PATH = () => {
    if (window.location.host.includes("localhost:")) {
        return "/dist/questlist.txt";
    } else {
        return window.location.host + "/dist/questlist.txt";
    }
};

解决建议

  1. 确认部署后文件的实际位置
    查看GitHub Pages工作流里Display _site Contents步骤的输出,确认questlist.txt最终在_site里的路径。因为Jekyll把./dist作为源目录构建,所以最终部署的网站根目录对应_site,dist不会出现在URL里。

  2. 修正fetch路径

    • 如果questlist.txt在_site/Quests/下,部署后的路径应该是/Quests/questlist.txt
    • 本地开发时如果需要保留/dist/Quests/questlist.txt,就用环境判断区分:
      const QUEST_FILE_PATH = window.location.host.includes("localhost:") 
        ? "/dist/Quests/questlist.txt"
        : "/Quests/questlist.txt";
      

    注意:绝对路径必须以/开头,避免React Router当前路由(比如/Quest)影响相对路径解析。

  3. 修复环境判断的错误
    之前的判断里,生产环境返回的window.location.host + "/dist/questlist.txt"会生成类似username.github.io/dist/questlist.txt的错误路径,正确的应该是直接用根相对路径/Quests/questlist.txt。

  4. 检查文件大小写
    GitHub Pages是区分大小写的,确认本地文件路径的大小写和代码里的一致(比如Quests和quests)。

内容的提问来源于stack exchange,提问作者Tanner Dunham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 09:15:57