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);
});
Related
I am sending a HTTP GET request from a browser to an external API using React. I'm getting a response containing some HTML and Javascript which I would like to render in my browser.
Here's my code so far:
const url = getExternalEndpoint()
fetch(url)
.then(function(response) {
return response.text();
}).then(function(data) {
console.log(data);
})
Based on Retrieve data from a ReadableStream object?
So I can see the HTML in the console, but I'm not sure how to render it.
For context, the external server I'm sending the request to is an OpenID Connect server.
So, there is one library called react-html-parser
To install, use the following command
npm install react-html-parser
# or
yarn add react-html-parser
Here, you can use the state to update the value from API.
import ReactHtmlParser from 'react-html-parser';
const [html_string, Sethtml_string] = useState('')
//set value in the html_string
<div> { ReactHtmlParser (html_string) } </div>
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.
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)
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
I've made GET requests to the github API:
axios.get('https://api.github.com/users/roadtocode822')
.then(function (response) {
console.log(response.data);
})
I get the response data. This function lives in the app.js file.
Also lives on the app.js file is the following code:
app.get('/', function(req, res){
Article.find({}, function(err, articles){
if(err){
console.log(err);
} else {
res.render('index', {
title: "Articles",
articles: articles
});
}
});
});
I'm able to query data from my mongodb database through the Article.js mongoose model and send the data to my index.pug file.
I want to be able to take the GITHUB response data and also render it in one of my pug view files. I feel like I'm missing some sort of concept in Javascript that's preventing me from achieving this.
Thanks in advance.
To get the Github response as a JSON, just use JSON.parse(). You won't be able to use your .pug template on the front end, however. That template is interpreted on the server side and is sent from server to client as plain old HTML. If you're interested in front-end templating, check out something like handlebars.js.
axios.get('https://api.github.com/users/roadtocode822')
.then(function (response) {
console.log(response.data);
})
from the code above, response.data will be a html content because your server returns res.render.
in the front-end, you should use a tag and form post instead of ajax call like this
Click