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

新手求助:如何连接部署在gh-pages的前端与Heroku的后端?

Hey there! Let's break down exactly what you need to modify on both your GitHub Pages frontend and Heroku backend to get them talking to each other smoothly. I'll keep this straightforward since you're new to this—no jargon overload!

1. Heroku Backend (server.js) Modifications

The biggest hurdle here is CORS (Cross-Origin Resource Sharing)—since your frontend lives on GitHub Pages' domain and your backend is on Heroku's, browsers will block requests by default unless you explicitly allow them. Here's how to fix it:

  • First, install the CORS dependency in your backend project:
    npm install cors
    
  • Update your server.js to import and configure CORS to allow your GitHub Pages domain:
    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    // Replace with your actual GitHub Pages URL (e.g., https://your-username.github.io/your-repo)
    const allowedOrigins = ['https://your-username.github.io'];
    
    // Configure CORS to only accept requests from your frontend
    app.use(cors({
      origin: function(origin, callback) {
        // Allow local testing (no origin) or requests from your allowed domain
        if (!origin || allowedOrigins.includes(origin)) {
          callback(null, true);
        } else {
          callback(new Error('Not allowed by CORS'));
        }
      }
    }));
    
    // Your existing backend routes (example below)
    app.get('/api/hello', (req, res) => {
      res.json({ message: 'Hi from your Heroku backend!' });
    });
    
    // Make sure to use Heroku's assigned port (or 3000 for local testing)
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
    
  • Double-check your package.json has a start script (Heroku needs this to launch your server):
    "scripts": {
      "start": "node server.js"
    }
    
  • Commit these changes and redeploy to Heroku (either via Git or the Heroku dashboard).
2. GitHub Pages Frontend (app.js) Modifications

You just need to point your frontend requests to your live Heroku backend instead of a local server:

  • Find any fetch or API call in your app.js that uses localhost (like http://localhost:3000/api/hello) and replace it with your Heroku app's URL. For example:
    // Before (local testing)
    // fetch('http://localhost:3000/api/hello')
    
    // After (pointing to Heroku)
    fetch('https://your-heroku-app-name.herokuapp.com/api/hello')
      .then(response => response.json())
      .then(data => {
        console.log(data);
        // Example: Display the backend message on your page
        document.getElementById('backend-message').textContent = data.message;
      })
      .catch(error => console.error('Error connecting to backend:', error));
    
  • If you haven't already, add an element to your index.html to display the backend data (optional but helpful for testing):
    <div id="backend-message"></div>
    
  • Commit these changes to your GitHub repo's gh-pages branch, wait a minute or two for GitHub Pages to update, and then test your frontend.
Quick Troubleshooting Tips
  • Test your Heroku backend first: Visit your Heroku API URL directly in a browser (e.g., https://your-heroku-app-name.herokuapp.com/api/hello) to make sure it returns a valid JSON response.
  • If you get CORS errors, double-check that your GitHub Pages URL in allowedOrigins is exactly correct (including https:// and no trailing slashes unless needed).
  • GitHub Pages can take 5-10 minutes to update after pushing changes—don't panic if you don't see updates right away!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:19:46