I am new to Angular and FastApi. I have been trying a scenario where I am invoking 2 separate FastApi end points from an Angular screen.
- I put the same Python code for a POST API in 2 separate .py files. Code provided below.
- The above python services are running on localhost, Port 8000 and Port 8001
- Now I am invoking each of these post end points from my angular app(running at localhost:4200). Code provided below.
Python Code
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
# from starlette.middleware.cors import CORSMiddleware
# from starlette.middleware import Middleware
class Item(BaseModel):
name: str
description: str | None= None
price: float
tax: float | None= None
origins = [
"*"
]
app = FastAPI();
app.add_middleware(
CORSMiddleware,
allow_origins = origins,
allow_credentials = False,
allow_methods = ["*"],
allow_headers = ["*"]
)
@app.post("/items/")
async def root(item: Item):
return item
Angular Code
onClickTest(){
const test = new Post("John","Desc",1,2);
console.log("Clicked...");
this.
httpClient.
post('http://127.0.0.1:8001/items',test).subscribe(
(response) => {
console.log(response)
},
(error) => {
console.log(error)
}
)
// const post = new Test("John");
this.
httpClient.
post('http://127.0.0.1/8000/items',test).subscribe(
(response) => {
console.log(response)
},
(error) => {
console.log(error)
}
)
Now the request successfully get processed for the Fast Api service at Port 8001 while it gives an error of connection refused for the Fast Api Service at Port 8000. Trying to understand what might be causing that. The error message does not seem to provide much info. Thank you.
CodePudding user response:
The issue is likely due to a misconfiguration in the Angular code, specifically in the HTTP post requests. The first request is using the correct host address http://127.0.0.1:8001/items, while the second request is using an incorrect address http://127.0.0.1/8000/items. (Note: ":" instead of "/")
The correct host address for the second request should be http://127.0.0.1:8000/items.
To resolve the error, update the second request as follows:
this.
httpClient.
post('http://127.0.0.1:8000/items', test).subscribe(
(response) => {
console.log(response)
},
(error) => {
console.log(error)
}
)
CodePudding user response:
in one case you are calling 127.0.0.1:8001
which is correct, in the second case you are calling 127.0.0.1/8000
which is wrong. Replace /
with :