I made an API in python with flask that creates a public key private key pair and respond with the public key whenever you try to access the API. I need to access my API in my Javascript code, but nothing appears in the console like it should when I call the API, I know my API is working because I tested it with Insomnia.
My Python code:
# Import dependencies
from flask import Flask, jsonify, request
import rsa
# Initialise the encrytion keys
publicKey, privateKey = rsa.newkeys(2048)
# Initialise the flask app
app = Flask(__name__)
# Create the currentkey page
@app.route("/currentkey")
def show_publickey():
return jsonify({"publickey": publicKey.save_pkcs1(format='PEM').decode("utf-8")})
My Javascript code:
// Set the url to fetch
const url = 'http://127.0.0.1:5000/currentkey';
fetch(url)
// fetch() returns a promise. When we have received a response from the server,
// the promise's `then()` handler is called with the response.
.then((response) => {
// Our handler throws an error if the request did not succeed.
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
// Otherwise (if the response succeeded), our handler fetches the response
// as text by calling response.text(), and immediately returns the promise
// returned by `response.text()`.
return response.text();
})
// When response.text() has succeeded, the `then()` handler is called with
// the text, and we log it to the console.
.then((text) => {
console.log(text);
})
// Catch any errors that might happen, and display a message
// in the key box.
.catch((error) => {
console.log(`Could not fetch content: ${error}`);
});
I have tested my API with Insomnia and it returns the expected values, and I have also tried using a different API in my Javascript code and it acts as expected. It is only when I use them both together that it doesn’t work
Hugo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.