I’m building a URL shortener with FastAPI, and I’m running into a problem with redirects. When I try to redirect users, I get this error:
Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be “http” or “https” for CORS request.
Here’s the code for the redirect function:
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse
@link.get("/{url}")
async def redirect(db: db_dependency, url: str):
original_url_record = db.query(Urls).filter(Urls.short_url == url).first()
if original_url_record:
original_url = original_url_record.original_url
print(original_url)
return RedirectResponse(url=original_url)
else:
raise HTTPException(status_code=404, detail="URL not found")
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
I also allowed all origins in the CORS configuration and ensured original_url starts with “http://” or “https://” but it didn’t helped
How do I redirect user to another url conventionally and what themes I should be familliar to not make this mistakes?
Shahll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4