Пытаюсь получить ответ от python в js:
function function() {
fetch(`http://127.0.0.1:8000/file`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: Id })
})
.then(response => response.json())
.then(data => {
if (data.status === 'confirmed') {
clearInterval(function1); // Остановка запросов
console.log("Получен ответ confirmed от сервера");
document.getElementById("status").textContent = "123";
alert("123");
clearInterval(function1); // Останавливаем проверку
}
})
.catch(error => {
// Обработка ошибки
console.error("123", error);
});
}
Выдает ошибку в консоли браузера:
Access to fetch at 'http://127.0.0.1:8000/check_payment' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
python:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
router = APIRouter()
app = FastAPI()
origins = [
"http://localhost",
"http://localhost",
"https://127.0.0.1",
"https://api.trongrid.io/",
"http://127.0.0.1:8000/"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"], # Разрешить все методы
allow_headers=["*"], # Разрешить все заголовки
expose_headers=["*"]
)
@router.post("/file")
async def function(request: Request, db: Session = Depends(get_db)):
data = await request.json()
id = data.get("id")
transaction = db.query(models.Transaction).filter_by(id=id).first()
if not transaction:
raise HTTPException(status_code=404, detail="123")
user = db.query(User.w).filter_by(id=transaction.user_id).scalar()
if not user_w:
raise HTTPException(status_code=400, detail="123")
time_limit = timedelta(minutes=60)
if datetime.utcnow() - transaction.created_at > time_limit:
transaction.status = "declined"
db.commit()
return {"status": "declined"}
# Получение транзакций по адресу кошелька
url = f"123"
print(f"Отправка запроса")
response = requests.get(url)
print(f"Ответ {response.status_code}, {response.json()}")
if response.status_code == 200:
response_data = response.json()
data = response.json()
if response_data.get('success'):
transactions = response.json()
for tx in transactions['data']:
print(f"Транзакция: {tx}")
api_amount = int(tx["value"])
transaction.amount = int(transaction.amount *10**5)
print("api amount: ", api_amount)
print("transaction amount: ", transaction.amount)
if api_amount == transaction.amount and tx['block_timestamp'] != 0:
transaction.status = "confirmed"
break
else:
print("User not found")
db.commit()
return {"status": "confirmed"}
else:
print(f"Error getting transactions: {response.status_code}")
print(transaction.status)
return {"status": "pending"}
Дал только нужные отрывки кода, некоторые переменные и названия изменил.
В терминале выдает:
INFO: 127.0.0.1:61951 - "OPTIONS /123 HTTP/1.1" 405 Method Not Allowed
INFO: 127.0.0.1:61954 - "OPTIONS /123 HTTP/1.1" 405 Method Not Allowed
INFO: 127.0.0.1:61954 - "OPTIONS /123 HTTP/1.1" 405 Method Not Allowed
INFO: 127.0.0.1:61954 - "OPTIONS /123 HTTP/1.1" 405 Method Not Allowed
INFO: 127.0.0.1:61954 - "OPTIONS /123 HTTP/1.1" 405 Method Not Allowed
INFO: 127.0.0.1:61997 - "OPTIONS /123 HTTP/1.1" 405 Method Not Allowed