How to pull data from own Flask JSON route endpoint using Axios - javascript

I would like to save JSON data into a variable using Axios in Javascript. The route that produces the JSON endpoint is my own servers route http://123.4.5.6:7890/json. This works successfully with the following function:
async function getClasses() {
const res = await axios.get('http://123.4.5.6:7890/json');
}
However, I figure this won't work with someone else's server when they pull up my project, so what line of code would go into the http:// spot? My mentor recomended using 'http://localhost:5000/json' however this error occurs when I tried this.
Here 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)
When I go to the http://123.4.5.6:7890/json route in my browser. JSON does successfully appear in the browser. Thanks, and any help is appreciated

I think it's a CORS issue, you can use the below code to solve this issue.
var config = {
headers: {'Access-Control-Allow-Origin': '*'}
};
async function getClasses() {
const res = await axios.get('http://123.4.5.6:7890/json', config);
}

on your app.py or main.py file
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

Related

Data posted to flask endpoint from JS not processed in endpoint

I have written a simple todo app with react acting as a frontend and flask handling CRUD from a DB. The app is using axios to handle the requests; GET completes fine however when attempting to POST JSON the flask api returns a 400 error. Here's some condensed sample code.
JS POST function.
function testPost(){
axios.post('http://'+window.location.hostname+':8000/todo/', {
title: "test123",
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
Serverside
class Todo(Resource):
def post(self): # create a new todo
conn = pool.getconn()
cur = conn.cursor()
app.logger.info(request.form['title'])
cur.execute("INSERT INTO todo (task, done) VALUES (%s, %s)", (request.form['title'], False))
conn.commit()
app.logger.error(e)
cur.close()
pool.putconn(conn)
Other methods not shown
Then the rest of the server code attaching the resource to the api and the CORS setup (not shown in file order)
app = Flask(__name__)
CORS(app, methods=['POST','GET','PUT','DELETE'])
api = Api(app)
api.add_resource(Todo, '/todo/')
app.run(debug = True, host='0.0.0.0', port=port)
Tests
Using python to test the api works fine, running this in a seperate python file will add to the DB.
response = requests.post(URL + "todo/", data={"title": f"test{randint(1, 100)}"})
My best guess is that axios is not adding the data to the request in a way that the backend is unable to process. Before using axios I tried to make the request with XMLHttprequest however this presented the same problem. I swapped to axios on the recommendation of someone else, given its alleged improved simplicity.
request.form['key'] and request.get_json()['key'] are completely different fields python requests in the way I used it posts to the former and js posts to the latter. Modifying the function to use whichever is available fixes this.

Lowdb (json database) with Next.js via Netlify returns internal server error 500 on API route, works locally

I've got a really simple JSON flat file db setup that works when running locally but doesn't work once it's hosted on Netlify. I don't get any other error info besides a 500 error on the server. I get the error even if all I do is import the clusterDB object, so something is happening with the lowdb object. I've also tried using another json db library called StormDB and I get the same issue.
Return my API route with a static import of the json file (no db libraries) also works fine.
I'm new to Next.js and this seems related to maybe the SSR portion of things since the API routes run only on the server? Do I need to structure my files differently? Are these libraries not compatible? Lowdb says it works with Node, and everything works locally for me.
Here is my db init file (root/db/db.js)
import {Low, JSONFileSync} from 'lowdb'
// Cluster DB Setup
const adapter = new JSONFileSync('cluster-db.json')
const clusterDB = new Low(adapter)
// Initialize if empty
clusterDB.read()
clusterDB.data ||= { clusters: [] }
clusterDB.write()
export {clusterDB}
And my only API route (root/pages/api/clusters.js)
import {clusterDB} from '../../db/db'
export default async function handler(req, res) {
await clusterDB.read()
switch(req.method) {
case 'POST':
let newCluster = {severity: req.query.severity, comments: req.query.comments, date: req.query.date}
clusterDB.data.clusters.push(newCluster)
clusterDB.write()
res.status(200).json({status: "Success", cluster: newCluster})
break;
case 'GET':
if(clusterDB.data.clusters) {
res.status(200).json(clusterDB.data.clusters)
} else {
res.status(404).json({status: "404"})
}
break;
}
res.status(200).json({test: "yay"})
}

How do I fetch data from server using MySQL/PHP using Vuejs frontend framework

I am quite new to web programming. Currently, I am looking to import backend data from PHP/MySQL into the vuejs application. One of them that I don't understand is how the Axios really works and how can I import data through the PHP(MySQL backend database). The backend database is created through XML.
First and foremost, I installed the vue-Axios through this link https://www.npmjs.com/package/vue-axios. Next, I continued to read on the documentation and there are various types of codes( which I am unsure of where to apply). What I am looking for is how can I import a specific component/item (which contains data) with pictures. I appreciate the help in advance.
I will just post my answer here as a response to the comment of the OP and to provide better formatting.
import axios from 'axios'
export default {
name: 'home',
async mounted () {
let response = await axios('http://128.106.100.230/bistro/get_step1_1.php')
// do something with the response here...
},
}
response is an object. You can obtain your result using
response.data
or using es6's object destructuring:
let { data } = await axios('http://128.106.100.230/bistro/get_step1_1.php')

Get array from node.js (server-side)to react app.js (client-side)

I'm trying to get an array from node.js (server-side) to react app.js (client-side)
so I need to get files to array from node and send it to app.js it seems like module.exports from node and import from app.js does not work like this here is what I tried
node.js file:
const fs= require('fs');
const files=fs.readdirSync('../Movies');
module.exports={
movies:files
}
app.js file
import { movies } from "./server/server.js";
console.log(movies);
do have have to
You can't do it.
app.js in client, It can't import "./server/server.js"
But you can send array has name of file in that forder when render.
node.js:
const files=fs.readdirSync('../Movies');
// when user request your page (this example use ejs)
res.render('<your_ejs_file>', {
myFiles: files,
});
// in your_ejs_file, create variable:
<script>
var yourFiles = <%= JSON.stringify(myFiles)%>
</script>
yourFiles is array named of file in your_folder
If you want load file from server, you can use AJAX to load it.
I use name of variable diffrent to you avoid mistake them.
If you want to send data from server-side to the client-side, you can use AJAX (sending HTTP requests to the server using front-end JavaScript). There are also other useful packages that you can use to simplify your work, like request or axios

JS access to mongoengine backend

I have a model created with Mongoengine and Python but need to access this data from JS for visualization on a Flask web app. What's the best way to do this?
I know of Python Eve and eve-mongoengine but it feels like creating a rest interface just for JS access is a bit too heavy. Any other suggestions?
You don't have to make a full rest api. Just create a route that will return a JSON. Use Flask's jsonify and GET the JSON using axios, fetch, jQueryor whatever you like.
Example using axios:
# app.py
# import jsonify from Flask
...
#app.route('/data')
def return_json():
# query = you query
return jsonify(query)
Remember to add axios to you static files or use a CDN.
// main.js
var axios = require('axios');
axios.get('/data')
.then(function (response) {
// do something with your data
})
.catch(function (error) {
// handle errors, like console.log(error);
});

Categories

Resources