A guide on extracting information from a personal Flask JSON route endpoint with Axios

I am looking to store JSON data in a variable using Axios in Javascript. The JSON endpoint is generated by my own server's route http://123.4.5.6:7890/json. I have been successful with this function:

async function getClasses() {
    const res = await axios.get('http://123.4.5.6:7890/json');
}

However, I understand that this may not work if someone else accesses my project from their server. What should I use instead of 'http://' in the code? My mentor suggested 'http://localhost:5000/json', but when I tried it, I encountered an error.

https://i.stack.imgur.com/qE5zS.png

This is the python code for my JSON route:

@app.route('/json')
def display_json():
    """view/signup for available yoga classes using API"""

    serialized_classes = [c.serialize() for c in Classes.query.all()]

    return jsonify(serialized_classes)

Accessing the route in my browser successfully displays the JSON data. Thank you in advance for any assistance provided.

Answer №1

It seems like there may be a CORS problem here. The solution could involve implementing the following code snippet.

const corsOptions = {
    headers: {'Access-Control-Allow-Origin': '*'}
};

async function fetchContent() {
    const response = await axios.get('http://111.22.33.44:5678/data', corsOptions);
}

Answer №2

Within your main application file, such as app.py or main.py

import flask_cors
application = Flask(__name__)
flask_cors.CORS(application)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Snowflake SQL - Encoding JSON column values into a table

Within my TRR table, I have JSON values in each row (I have eliminated any null rows from TRR), and my goal is to separate these JSON rows into a table with corresponding columns See the TRR containing JSON values here It's important to note that ea ...

JQuery HTML form validation continues to send emails even when there are blank entries

I've set up an HTML form with three required fields, and I'm trying to prevent the form from submitting an AJAX call if those fields are left empty. $("#contact").submit(function(e){ e.preventDefault(); var ajaxurl = '<?php echo ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

Error message: Angular JS encountered an issue when trying to initiate the test module. The cause

When I run JavaScript within an HTML file and use AngularJS with ng-repeat function, I encounter this console error: angular.js:38 Uncaught Error: [$injector:modulerr] Clicking on the link in the error message leads to: Failed to instantiate module test ...

There seems to be an issue with VS Code: the function filter is not working as expected when applied to the result of

Recently, I've encountered a frustrating error in VS Code that is hindering my ability to create new files or open existing ones. The pop-up error message that appears states (this.configurationService.getValue(...) || []).filter is not a function Th ...

Achieving a delayed refetch in React-Query following a POST请求

Two requests, POST and GET, need to work together. The POST request creates data, and once that data is created, the GET request fetches it to display somewhere. The component imports these hooks: const { mutate: postTrigger } = usePostTrigger(); cons ...

What is the best way to deserialize a JavaScript date with Jackson library?

I receive a date string from ExtJS in the format: "2011-04-08T09:00:00" When attempting to deserialize this date, it automatically adjusts the timezone to Indian Standard Time (adding +5:30 to the time). Here is my current method for deserializing the ...

Is there a way to track dynamic changes in window dimensions within Vue?

Working on my Vue mobile web app, I encountered an issue with hiding the footer when the soft keyboard appears. I've created a function to determine the window height-to-width ratio... showFooter(){ return h / w > 1.2 || h > 560; } ...and ...

Iterate through an array index within a map function in a ReactJS component

I am working with a map that contains images of metros, and I need to increment the number by 1 at each loop iteration. For example, the first loop will display {metrosImages[0]}, then {metrosImages[1]}, and so on until the loop reaches its end. The code ...

Unnecessary socket.io connection in a React component

Incorporating socket.io-client into my react component has been a learning experience. Most tutorials recommend setting it up like this: import openSocket from 'socket.io-client'; const socket = openSocket('http://localhost:8000'); In ...

Is AJAX not functioning on Mac OS's Mozilla Firefox browser?

Using Rails 4 with an AJAX Call on Mac OS and Mozilla Browser _header.html.erb <span class="callno"><%= link_to "Log in", {:controller => "web",:action => "log_in_user"}, :role => 'button', 'data-toggle' => &a ...

Enhancing JSON.dumps function in Python's Requests Package for a GET Request with additional ampersands

My goal is to make a basic get request to a public API using the python requests library. I am working with requests version 2.25.1 and Python 3.6. The issue I'm facing is that there is an extra & appearing in the URL parameters, and I can't ...

bcrypt is failing to return a match when the password includes numeric characters

I've integrated node-bcrypt with PostgreSQL (using Sequelizejs) to securely hash and store passwords. In the process, the user's password undergoes hashing within a beforeValidate hook as shown below: beforeValidate: function(user, model, cb) { ...

Choosing read-only text fields using JQuery

I am working on an ASP.NET MVC project and I am looking to select all text boxes with the "readOnly" attribute on the current page. Once identified, I want to trigger a modal jQuery dialog on keypress for each of these disabled text boxes. Any suggestion ...

Allowing access from different domains when using Angular.js $http

Whenever I encounter a CORS issue while developing a webapp, my go-to solution is to brew some coffee. However, after struggling with it for some time, I am unable to resolve the problem this time and need assistance. Below is the client-side code snippet ...

Directing traffic from one webpage to another without revealing the file path in the Routes.js configuration

Recently starting out in Reactjs and utilizing Material-UI. My inquiry is regarding transitioning between pages using a sidebar, where in Material-UI it's required to display the page in the sidebar which isn't what I desire. var dashRoutes = [ ...

By changing the name of my file to .js.erb, I am able to seamlessly incorporate erb syntax within my javascript code, but this

Currently, I am using chessboard-0.3.0.js in a rails application. Due to the rails asset pipeline setup, I've had to make adjustments to the js code specifically related to rendering images, such as Pieces. In line 445 of chessboard.js, it states: c ...

Issue with Magnific Popup lightbox functionality, and mfp-hide is ineffective

Hello everyone, I am new to stackoverflow so please bear with me as I navigate through it. Although I am still a beginner in HTML, CSS, and JS, I have been using them for work on occasion. Recently, I implemented Magnific Popup on a website I am working o ...

What is the best way to manage uncaught errors within the simple-peer library?

Currently integrating feross' simple-peer library and encountering an occasional error: Uncaught Error: Ice connection failed. at r._onIceStateChange at RTCPeerConnection.t._pc.oniceconnectionstatechange This error is directly from the library and ...

The Ion-icon fails to appear when it is passed as a prop to a different component

On my Dashboard Page, I have a component called <DashHome /> that I'm rendering. I passed in an array of objects containing icons as props, but for some reason, the icons are not getting rendered on the page. However, when I used console.log() t ...