0

So I've been working on an api (using fastapi) that sends product prices on shopping sites. Ive done the server-side code with python. Everything seems to work when I type the end-point url on any browser, and even using regular python requests module. But when I was about to implement it using javascript XMLHTTPRequest, the request was sent to server, does what it should do, but not returning response. Here is the python code:

from fastapi import FastAPI
import scrape
import db

app = FastAPI()

@app.get("/")
def home():
        return {"you": "sus"}

@app.get("/add")
def add_url(url : str):
        vals = scrape.save_info(url)
        return vals

@app.get("/get")
def get_by_name(name : str):
        db.existing()
        vals = db.get_matching(name)
        db.end()
        return vals

@app.get("/get-all")
def get_all():
        db.existing()
        vals = db.show_all_values()
        db.end()
        print(vals)
        return vals

Here is the javascript

const request = new XMLHttpRequest();
const data = {
  get: {
    name: "test"
  }
};

function func()
{
  console.log(this.responseText);
};

const url = "http://127.0.0.1:8000/get-all";

request.addEventListener("load", func);

request.open("GET", url);
request.setRequestHeader("Content-Type", "text/plain")
request.send(JSON.stringify(data));

Vishu
  • 33
  • 3
  • What is the exact problem when you run this? – Paul P Oct 01 '22 at 08:58
  • You seem to be sending the request to your API through a frontend that is in a different origin; in that case, you would need to [enable CORS in the backend](https://stackoverflow.com/a/71805329/17865804). Also, please have a look at related answers [here](https://stackoverflow.com/a/71665594/17865804), [here](https://stackoverflow.com/a/73359311/17865804), as well as [here](https://stackoverflow.com/a/71741617/17865804), [here](https://stackoverflow.com/a/71891621/17865804) and [here](https://stackoverflow.com/a/70640522/17865804). – Chris Oct 01 '22 at 14:23

0 Answers0