I am trying to deploy my react app to GitHub pages without a custom URL. Almost everything works well and the page is successfully deployed. Although, when I go to the web address, it seems that the page does not communicate with the API. After checking the console these 3 errors and 1 warning show up:
[Warning] [blocked] The page at https://ambaks.github.io/auction-app/ requested insecure content from http://localhost:8000/emails. This content was blocked and must (main.93af0b37.js, line 2)
[Error] Not allowed to request resource
(anonymous function) (main.93af0b37.js:2:210042)
Promise
(anonymous function) (main.93af0b37.js:2:208038)
St (main.93af0b37.js:2:218033)
_request (main.93af0b37.js:2:221077)
(anonymous function) (main.93af0b37.js:2:219507)
request (main.93af0b37.js:2:219781)
(anonymous function) (main.93af0b37.js:2:224798)
(anonymous function) (main.93af0b37.js:2:224872)
(anonymous function) (main.93af0b37.js:2:224873)
Ii (main.93af0b37.js:2:84015)
Eu (main.93af0b37.js:2:99867)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:100549)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:99888)
tc (main.93af0b37.js:2:126626)
(anonymous function) (main.93af0b37.js:2:124005)
T (main.93af0b37.js:2:180662)
[Error] XMLHttpRequest cannot load http://localhost:8000/emails due to access control checks.
(anonymous function) (main.93af0b37.js:2:210042)
Promise
(anonymous function) (main.93af0b37.js:2:208038)
St (main.93af0b37.js:2:218033)
_request (main.93af0b37.js:2:221077)
(anonymous function) (main.93af0b37.js:2:219507)
request (main.93af0b37.js:2:219781)
(anonymous function) (main.93af0b37.js:2:224798)
(anonymous function) (main.93af0b37.js:2:224872)
(anonymous function) (main.93af0b37.js:2:224873)
Ii (main.93af0b37.js:2:84015)
Eu (main.93af0b37.js:2:99867)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:100549)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:99888)
tc (main.93af0b37.js:2:126626)
(anonymous function) (main.93af0b37.js:2:124005)
T (main.93af0b37.js:2:180662)
[Error] Error fetching emails: – Q {stack: "@https://ambaks.github.io/auction-app/static/js/ma…o/auction-app/static/js/main.93af0b37.js:2:219600", message: "Network Error", name: "AxiosError", …}
Q {stack: "@https://ambaks.github.io/auction-app/static/js/ma…o/auction-app/static/js/main.93af0b37.js:2:219600", message: "Network Error", name: "AxiosError", code: "ERR_NETWORK", config: Object, …}Q
(anonymous function) (main.93af0b37.js:2:224842)
I tried creating a custom certificate and running my localhost on server like they did at this link but it didn’t work for me.
Here is my backend code:
database.py
:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base
URL_DATABASE = 'sqlite:///./emails.db'
engine = create_engine(URL_DATABASE, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
main.py
:
'''
FastAPI app
'''
from database import Base
from fastapi import FastAPI, HTTPException, Depends
from typing import Annotated, List
from sqlalchemy.orm import Session
from pydantic import BaseModel
from database import SessionLocal, engine
import models
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
'*'
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*']
)
class EmailBase(BaseModel):
email: str
class EmailModel(EmailBase):
id: int
class Config:
orm_mode=True
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
db_dependency = Annotated[Session, Depends(get_db)]
Base.metadata.create_all(bind=engine)
@app.post('/emails', response_model=EmailModel)
async def create_email(email: EmailBase, db: db_dependency):
db_email = models.Email(**email.model_dump())
db.add(db_email)
db.commit()
db.refresh(db_email)
return db_email
@app.get('/emails', response_model=List[EmailModel])
async def read_emails(db: db_dependency, skip: int = 0, limit: int = 100):
emails = db.query(models.Email).offset(skip).limit(limit).all()
return emails
models.py:
from database import Base
from sqlalchemy import Column, Integer, String
class Email(Base):
__tablename__ = 'emails'
id = Column(Integer, primary_key=True, index=True)
email = Column(String)
And here is the code for my react frontend:
api.js
:
import axios from 'axios';
const api = axios.create({
baseURL: 'https://localhost:8000'
});
// Export axios instance
export default api;
app.js
:
import React, { useState, useEffect } from 'react';
import api from './api';
const App = () => {
const [emails, setEmails] = useState([]);
const [formData, setFormData] = useState({ email: '' });
useEffect(() => {
const fetchEmails = async () => {
try {
const response = await api.get('/emails'); // Fetch emails
setEmails(response.data);
} catch (error) {
console.error('Error fetching emails:', error);
}
};
fetchEmails();
}, []);
const handleFormSubmit = async (event) => {
event.preventDefault();
try {
await api.post('/emails', formData); // Submit email
setFormData({ email: '' });
const response = await api.get('/emails'); // Refresh email list
setEmails(response.data);
} catch (error) {
console.error('Error submitting email:', error);
}
};
const handleInputChange = (event) => {
setFormData({ email: event.target.value });
};
return (
<div >
<nav className="navbar navbar-dark bg-primary">
<div className="container-fluid">
<a className="navbar-brand" href="#">
Naia App
</a>
</div>
</nav>
<div className="container mt-4">
<form onSubmit={handleFormSubmit}>
<div className="mb-3">
<label htmlFor="emailInput" className="form-label">Email</label>
<input
type="email"
className="form-control"
id="emailInput"
value={formData.email}
onChange={handleInputChange}
required
/>
</div>
<button type="submit" className="btn btn-primary">Add Email</button>
</form>
</div>
</div>
);
}
export default App;
This is what my package.json
looks like:
{
"name": "react-frontend",
"homepage": "https://ambaks.github.io/auction-app",
"version": "0.1.0",
"private": false,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"axios": "^1.7.9",
"gh-pages": "^6.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "react-scripts start",
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
And this is my index.html
:
<!doctype html>
<html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="./auction-app/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"><link rel="apple-touch-icon" href="./auction-app/logo192.png"/><link rel="manifest" href="./auction-app/manifest.json"/><title>React App</title><script defer="defer" src="./auction-app/static/js/main.25947243.js"></script><link href="./auction-app/static/css/main.e6c13ad2.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script></body></html>
2
Answers
You can host your Python codes on PythonAnywhere. PythonAnywhere is an easy-to-use web-based Python development environment and web hosting service (PaaS) that can be accessed from any device with a browser.
You can sign up for the free tier and host your Python backend at no cost. Then you can get endpoints to consume your API from the frontend.
See The PythonAnywhere API (beta) and Integrating a development environment with PythonAnywhere
"Verify API endpoint URLs are absolute. Check CORS headers on your API server. Ensure GitHub Pages settings are correct. Inspect browser console errors and network requests. Consider proxying API requests. Provide more details: