Trying to use fastapi with next.js But idk why is it not working
Answered
Chinese Alligator posted this in #help-forum
Chinese AlligatorOP
Guys im getting this error :
My app.py inside /api :
next config :
When i try to go to localhost:3000/api/docs
I get this error :
Error: connect ECONNREFUSED 127.0.0.1:8000
at TCPConnectWrap.afterConnect [as oncomplete] (node
1595:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8000
}
â—‹ Compiling /_error ...
✓ Compiled /_error in 8.1s (2990 modules)
What is this? can someone please help me?
Error: connect ECONNREFUSED 127.0.0.1:8000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1595:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8000
}
â—‹ Compiling /_error ...
✓ Compiled /_error in 8.1s (2990 modules)My app.py inside /api :
from fastapi import FastAPI, HTTPException, Body
from fastapi.middleware.cors import CORSMiddleware
import httpx
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
discord_webhook_url = "https://discord.com/api/webhooks/"
@app.post("/api/send-message")
async def send_message(
data: dict = Body(...),
):
try:
name = data['name']
email = data['email']
message = data['message']
except KeyError as e:
raise HTTPException(status_code=422, detail=f"Missing required field: {e}")
print(f"Received data: Name={name}, Email={email}, Message={message}")
form_data = {
"content": "New message from website",
"username": f"New Message from {email}",
"embeds": [
{
"title": "New Message",
"description": f"**Name:** {name}\n**Email:** {email}\n**Message:** {message}",
"color": 16777215
}
]
}
try:
async with httpx.AsyncClient() as client:
response = await client.post(discord_webhook_url, json=form_data)
if response.status_code != 204:
raise HTTPException(status_code=response.status_code, detail="Failed to send message to Discord")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error sending message to Discord: {str(e)}")
return {"message": "Message sent successfully"}next config :
/** @type {import('next').NextConfig} */
const nextConfig = {
rewrites: async () => {
return [
{
source: "/api/:path*",
destination:
process.env.NODE_ENV === "development"
? "http://127.0.0.1:8000/api/:path*"
: "/api/",
},
];
},
};
module.exports = nextConfig;
When i try to go to localhost:3000/api/docs
I get this error :
Error: connect ECONNREFUSED 127.0.0.1:8000
at TCPConnectWrap.afterConnect [as oncomplete] (node
1595:16)at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8000
}
â—‹ Compiling /_error ...
✓ Compiled /_error in 8.1s (2990 modules)
What is this? can someone please help me?
Answered by Chinese Alligator
The problem was i didn't had this line "dev": "concurrently "npm run next-dev" "npm run fastapi-dev"",
13 Replies
Chinese AlligatorOP
There is literally 0 info about this on internet
idk how fastify works but like is the fastify server running when you are doing this?
@Clown idk how fastify works but like is the fastify server running when you are doing this?
Chinese AlligatorOP
*FastAPI
It should be running with Node runtime
But nothing is happening
well you need to make your fastapi server is running beforehand
how are you starting it?
ah i see, its mapped to "dev" script in the starter
@Chinese Alligator try what noobkid sent and also if it doesnt work make sure you see if pip is installed.
also this starter sets the pip command to "pip3", change that to "pip" if thats what the executable is named for you
also this starter sets the pip command to "pip3", change that to "pip" if thats what the executable is named for you
Chinese AlligatorOP
Yeah i got it
Chinese AlligatorOP
The problem was i didn't had this line "dev": "concurrently "npm run next-dev" "npm run fastapi-dev"",
Answer
Chinese AlligatorOP
solved