最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to fetch and Display HTML Content from Public Directory - Stack Overflow

programmeradmin0浏览0评论

Need help with Vite + React, where one is unable to fetch and display content from the public directory. Despite following various troubleshooting steps, the content from the projects home.html is not being displayed in the React component. There are no logs in the console of the browser. Following is a snapshot of the network and console logs fro the browser. One understands it isn't a good practice to post images here but without it one cannot view the actual result or understand the problem.

enter image description here

Project Setup:

├── @vitejs/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

vite.config.js: In the main project directory

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist',
    rollupOptions: {
      input: {
        main: 'index.html',
        admin: 'admin.html',
      },
    },
  },
  server: {
    open: true,
    host: '127.0.0.1', // Set host to 127.0.0.1
    historyApiFallback: true, // Ensure SPA fallback
  },
  base: './', // Set base path
});

publicHome.jsx: In the public/src directory

import React, { useEffect, useState } from 'react';

const PublicHome = () => {
  const [content, setContent] = useState('');

  useEffect(() => {
    // Fetch content from home.html in the public directory
    fetch('/home.html')
      .then(response => response.text())
      .then(data => setContent(data))
      .catch(error => console.error('Error fetching home.html content:', error));
  }, []);

  return (
    <div dangerouslySetInnerHTML={{ __html: content }} />
  );
};

export default PublicHome;

index.html: In the main project directory and not in the public directory

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Entry Point</title>
</head>
<body>
    <script>
        // Redirect to home.html as the default landing page
        if (window.location.pathname === '/' || window.location.pathname === '/index.html') {
            window.location.href = 'home.html';
        }
    </script>
</body>
</html>

Steps taken is as follows..

Verified that home.html and test.html are in the public directory. Ensured the fetch path in publicHome.jsx is correct. Checked the browser's developer console for errors. Cleared NPM cache and rebuilt the project using the following commands multiple times

npm cache clean --force
rmdir /s /q node_modules
rmdir /s /q dist
npm install
npm run build
npx serve -s dist

Despite following the said steps, the content from home.html is not being displayed in the React component. The network request for the HTML files is successful, but the content is not rendered.

Any insights or suggestions on how to resolve this issue would be greatly appreciated. Thank you!

Need help with Vite + React, where one is unable to fetch and display content from the public directory. Despite following various troubleshooting steps, the content from the projects home.html is not being displayed in the React component. There are no logs in the console of the browser. Following is a snapshot of the network and console logs fro the browser. One understands it isn't a good practice to post images here but without it one cannot view the actual result or understand the problem.

enter image description here

Project Setup:

├── @vitejs/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

vite.config.js: In the main project directory

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist',
    rollupOptions: {
      input: {
        main: 'index.html',
        admin: 'admin.html',
      },
    },
  },
  server: {
    open: true,
    host: '127.0.0.1', // Set host to 127.0.0.1
    historyApiFallback: true, // Ensure SPA fallback
  },
  base: './', // Set base path
});

publicHome.jsx: In the public/src directory

import React, { useEffect, useState } from 'react';

const PublicHome = () => {
  const [content, setContent] = useState('');

  useEffect(() => {
    // Fetch content from home.html in the public directory
    fetch('/home.html')
      .then(response => response.text())
      .then(data => setContent(data))
      .catch(error => console.error('Error fetching home.html content:', error));
  }, []);

  return (
    <div dangerouslySetInnerHTML={{ __html: content }} />
  );
};

export default PublicHome;

index.html: In the main project directory and not in the public directory

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Entry Point</title>
</head>
<body>
    <script>
        // Redirect to home.html as the default landing page
        if (window.location.pathname === '/' || window.location.pathname === '/index.html') {
            window.location.href = 'home.html';
        }
    </script>
</body>
</html>

Steps taken is as follows..

Verified that home.html and test.html are in the public directory. Ensured the fetch path in publicHome.jsx is correct. Checked the browser's developer console for errors. Cleared NPM cache and rebuilt the project using the following commands multiple times

npm cache clean --force
rmdir /s /q node_modules
rmdir /s /q dist
npm install
npm run build
npx serve -s dist

Despite following the said steps, the content from home.html is not being displayed in the React component. The network request for the HTML files is successful, but the content is not rendered.

Any insights or suggestions on how to resolve this issue would be greatly appreciated. Thank you!

Share Improve this question edited Mar 6 at 8:55 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Mar 6 at 8:30 devOpdevOp 12 bronze badges 2
  • Your post contains several indicators that ChatGPT or another LLM was used to generate it. For a variety of reasons, the use of such generative AI tools is strictly disallowed on Stack Overflow. Please edit your question to remove and replace content that was generated using these tools. – esqew Commented Mar 6 at 9:13
  • According to the screenshot, /home.html appears to automatically redirect to /home. So why are you explicitly trying to load / assign /home.html in multiple places to begin with? – C3roe Commented Mar 6 at 9:22
Add a comment  | 

1 Answer 1

Reset to default 0

Did you try troubleshooting the fetch?

You can add a line to log the content to the console (instead of only log the error). You can check the query in network developer tools as well; there you'll find useful information.

I couldn't find the error either.

发布评论

评论列表(0)

  1. 暂无评论