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

如何不使用Node、Express等后端技术创建可部署的REST API?

Can I build a REST API with only React/Vue (no Node/Express) for GitHub/GitLab Pages?

Absolutely! You can build a fully functional API that meets all your requirements using just a frontend framework like React or Vue—no backend servers required. Since GitHub/GitLab Pages host static content, we’ll combine static file hosting for your quotes.txt with frontend routing to simulate the API endpoints you need. The end result will be a deployable API accessible via your custom domain (like http://username.github.io) that behaves just like a traditional REST API for GET requests.

Core Approach

  1. Static quotes.txt: Place your quotes file in the public/static directory of your frontend project. This lets GitHub Pages serve it directly at /quotes.txt (fulfilling your first endpoint requirement out of the box).
  2. Frontend Routing: Use React Router (for React) or Vue Router (for Vue) to match your other API paths (/quotes.json, /random.txt, /random.json).
  3. Client-Side Processing: For each routed endpoint, fetch the static quotes.txt file, process the content into the required format (JSON/random quote), and dynamically set the page’s content and Content-Type header to mimic a real API response.

Step-by-Step with React

Let’s walk through building this with React:

1. Set Up the Project

npx create-react-app quote-api
cd quote-api
npm install react-router-dom

2. Add Your quotes.txt

Create a quotes.txt file in the public/ directory with your quotes (one per line):

The greatest glory in living lies not in never falling, but in rising every time we fall. - Nelson Mandela
The way to get started is to quit talking and begin doing. - Walt Disney
Your time is limited, so don't waste it living someone else's life. - Steve Jobs

3. Configure Routing

Update src/App.js to define your API routes:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import QuotesJson from './components/QuotesJson';
import RandomTxt from './components/RandomTxt';
import RandomJson from './components/RandomJson';

function App() {
  return (
    <Router>
      <Routes>
        {/* /quotes.txt is served directly by GitHub Pages (no routing needed) */}
        <Route path="/quotes.json" element={<QuotesJson />} />
        <Route path="/random.txt" element={<RandomTxt />} />
        <Route path="/random.json" element={<RandomJson />} />
        {/* Optional: Home page with API docs */}
        <Route path="/" element={
          <div style={{ padding: '2rem' }}>
            <h1>Quote API</h1>
            <p>Available endpoints:</p>
            <ul>
              <li><code>/quotes.txt</code> - Raw quotes text</li>
              <li><code>/quotes.json</code> - Quotes as JSON array</li>
              <li><code>/random.txt</code> - Random quote (plain text)</li>
              <li><code>/random.json</code> - Random quote (JSON)</li>
            </ul>
          </div>
        } />
      </Routes>
    </Router>
  );
}

export default App;

4. Build the API Components

Create these components in src/components/:

QuotesJson.js (returns quotes as JSON)

import { useEffect } from 'react';

const QuotesJson = () => {
  useEffect(() => {
    fetch('/quotes.txt')
      .then(res => res.text())
      .then(text => {
        const quotes = text.split('\n').filter(line => line.trim() !== '');
        const jsonContent = JSON.stringify({ quotes }, null, 2);
        
        // Format response like a real API
        document.body.innerHTML = jsonContent;
        document.contentType = 'application/json';
      })
      .catch(err => {
        document.body.innerHTML = JSON.stringify({ error: 'Failed to load quotes' }, null, 2);
        document.contentType = 'application/json';
      });
  }, []);

  return <div></div>;
};

export default QuotesJson;

RandomTxt.js (returns random quote as plain text)

import { useEffect } from 'react';

const RandomTxt = () => {
  useEffect(() => {
    fetch('/quotes.txt')
      .then(res => res.text())
      .then(text => {
        const quotes = text.split('\n').filter(line => line.trim() !== '');
        const randomQuote = quotes.length ? quotes[Math.floor(Math.random() * quotes.length)] : 'No quotes available';
        
        document.body.innerHTML = randomQuote;
        document.contentType = 'text/plain';
      })
      .catch(err => {
        document.body.innerHTML = 'Error loading random quote';
        document.contentType = 'text/plain';
      });
  }, []);

  return <div></div>;
};

export default RandomTxt;

RandomJson.js (returns random quote as JSON)

import { useEffect } from 'react';

const RandomJson = () => {
  useEffect(() => {
    fetch('/quotes.txt')
      .then(res => res.text())
      .then(text => {
        const quotes = text.split('\n').filter(line => line.trim() !== '');
        const content = quotes.length 
          ? JSON.stringify({ quote: quotes[Math.floor(Math.random() * quotes.length)] }, null, 2)
          : JSON.stringify({ quote: 'No quotes available' }, null, 2);
        
        document.body.innerHTML = content;
        document.contentType = 'application/json';
      })
      .catch(err => {
        document.body.innerHTML = JSON.stringify({ error: 'Failed to load random quote' }, null, 2);
        document.contentType = 'application/json';
      });
  }, []);

  return <div></div>;
};

export default RandomJson;

5. Deploy to GitHub Pages

  1. Install the deployment tool:
npm install gh-pages --save-dev
  1. Update package.json to add your repo URL and deploy scripts:
"homepage": "https://your-username.github.io/quote-api",
"scripts": {
  // ... existing scripts
  "predeploy": "npm run build",
  "deploy": "gh-pages -d build"
}
  1. Deploy:
npm run deploy

Quick Vue Alternative

The same logic applies to Vue:

  1. Create a Vue project, install Vue Router.
  2. Place quotes.txt in public/.
  3. Define routes for /quotes.json, /random.txt, /random.json.
  4. In each route component’s onMounted hook, fetch quotes.txt, process the content, and update the document’s content and Content-Type.

Example QuotesJson.vue:

<template>
  <div></div>
</template>

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  fetch('/quotes.txt')
    .then(res => res.text())
    .then(text => {
      const quotes = text.split('\n').filter(line => line.trim());
      document.body.innerHTML = JSON.stringify({ quotes }, null, 2);
      document.contentType = 'application/json';
    })
    .catch(err => {
      document.body.innerHTML = JSON.stringify({ error: 'Failed to load quotes' }, null, 2);
      document.contentType = 'application/json';
    });
});
</script>

Key Notes

  • Custom Domain: Set up your custom domain directly in GitHub/GitLab Pages settings—no backend changes needed.
  • Static File Behavior: /quotes.txt is served natively by Pages, so it’s fast and reliable.
  • Limitations: This approach only supports GET requests (since it’s static hosting). If you ever need POST/PUT/DELETE, you’d need a backend service, but your requirements are fully covered here.
  • Testing: Test your endpoints in browsers or tools like Postman—they’ll behave exactly like traditional API responses.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:26:53