I'm working on the front-end of an API in react and I'm trying to get the ten first items of a JSON list like:
[{"element1":"value", "element2":"value"}, {"element1":"other value", "element2":"other value"}, ...]
But I don't know how to do that with Axios :/
I found nothing in the Axios' Docs or on this forum
Thanks for your help :)
What you are talking about is called pagination and this feature should be implemented on the back end. If pagination is not supported by the backend, then you just have to use regular js array methods, for example, slice https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Ok, so what you are going to want to use is headers with Axios. Like this:
// headers are like variables that tell your backend what it needs to know
const config = {
headers: {
numberOfElements: 5
}
}
axios.get('/apiendpoint', config)
.then((response) => {
// what your backend is sending the frontend
console.log(response);
})
Then in your backend you can get the data from that header with express and serve your data:
const express = require('express');
const app = express();
// here is your example data
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
app.get('/urlendpoint', (req, res) => {
// use the req.get method to get the header data
const numberOfElements = req.get('numberOfElements');
// now we can use the arrays .slice() method to get the first x elements of an array and send it in the response
res.send(numbers.slice(0, numberOfElements));
});
you can read more about the .slice method here
Related
` methods: {
async getData() {
const xata = getXataClient();
const page = await xata.db.quiz
.select(["questions", "answer", "options", "selected"])
.getPaginated({
pagination: {
size: 15,
},
});
console.log(page.records);
},
},`
I'm new to Xata data base, and i've created a data base but i can't query xata using vue js
You actually can’t query Xata from vue since it’s a frontend framework (more information on why you shouldn’t do this here -> https://xata.io/blog/securely-querying-your-database-on-xata)
If you want help, I invite you to join xata’s discord channel
Have fun!
I've read through numerous answers on SO, but most don't show both the Flask and JS side of my question, so I don't believe this is a duplicate. Specifically, using React/JS, I'm attempting to fetch a list of dictionaries from my Flask API.
On the server side, I've successfully serialized my class, and can print the list of dictionaries as expected. However, after I return it using JSONIFY (as suggested in several SO questions), it results in undefined on the JS side when I try to access the data. From reading online, it appeared that I could attempt to JSON parse the response data, but this similarly shows undefined. This leads me to believe that the issue may in fact be on the server side. Regardless, I'm also unsure how to properly access this list of dictionaries in my fetch function (I would've expected that I can do something along the lines of data[0]['name']).
I'd really appreciate any guidance you might have - thank you for reading this far.
eqtls prints as follows in api.py:
[{'id': 1, 'name': 'Bearbrook Skateboard Park', 'description': 'Flat asphalt surface, 5 components', 'xcoord': -75, 'ycoord': 45, 'date_added': datetime.datetime(2021, 10, 26, 19, 46, 10)}]
api.py
class Activity(db.Model):
id = db.Column(db.Integer, primary_key=True)
xcoord = db.Column(db.Integer,nullable=False)
ycoord = db.Column(db.Integer, nullable=False)
name = db.Column(db.String(200))
description = db.Column(db.String(200))
date_added = db.Column(db.DateTime, default = datetime.utcnow)
#create a string
def __repr__(self):
return f"<id={self.id}, name={self.name},description={self.description},xcoord={self.xcoord},ycoord={self.ycoord},date_added={self.date_added}>"
def serialize(self):
return {
'id': self.id,
'name': self.name,
'description': self.description,
'xcoord': self.xcoord,
'ycoord': self.ycoord,
'date_added': self.date_added
}
#app.route('/allActivities', methods=['GET'])
def allActivities():
print('hit allActivities routing')
allActivities = Activity.query.all()
print(str(allActivities))
eqtls=[activity.serialize() for activity in allActivities]
print(str(eqtls))
sys.stdout.flush()
return jsonify(eqtls)
Currently in app.js, my data variable logs as undefined.
app.js
useEffect(()=> {
fetch('/allActivities').then(response => {
if(response.ok){
console.log(response)
return response.json()
}
}).then(data => setAllActivities(data))
.then(data => {
console.log(data);
//var jsonData = JSON.parse((data));
//console.log(jsonData[0].name);
})
},[])
I want to define the response structure of my requests in the simplest way, and the first thing that comes in my mind to do this is a middleware.
My endpoints are returning the response content correctly:
{{base_url}}/users returns a list of users:
{
[
{
"id": 44,
"name": "some name"
[...]
}
]
}
What I want to do (in all requests) is to add the fields status and data (or any other I'd like to add), like this:
{
"status": 200,
"data": [
{
"id": 44,
"name": "some name"
[...]
}
]
}
I've created a middleware that waits for the resolution but I'm not able to get the content nor add some property to it.
[...]
async handle ({request, response}, next) {
await next()
const content = response._lazyBody.content
content.status = response.response.statusCode
}
[...]
I know this will not work but I want something similar to this. I've looked in Adonis docs and forum, but no answers fit to my needs.
Any help will be welcome
You can extend Response By extending the core. The simplest way is to create a file inside start folder and name it hooks.js and copy and paste the content below inside it:
const { hooks } = use('#adonisjs/ignitor')
const Response = use('Adonis/Src/Response')
hooks.after.providersBooted(() => {
Response.macro('customJson', function (status, data) {
this.status(status).json({
status,
data
})
})
})
this piece of code extends the Response module and add customJson method to it which takes two arguments, status and data, and send them back to the client.
And here you can see how to use it:
Route.get('/users', async ({ response }) => {
let status = ''// whatever you want
let data = ''// whatever you want
return response.customJson(status, data)
})
I need to continuously make this http.get request from an API that sends back location data
So i tried writing a basic get reuest to check if the data is coming through, and it is, the problem is I need it in a continuous loop every second the gps device sends data.
http.get(_url2, res =>{
let body='';
res.on("data", data =>{
body+=data;
})
res.on("end",()=>{
body = JSON.parse(body);
gpsData.push(body.data);
console.log('gpsData Array : ',gpsData)
})
})
I get this logged out to the console,
$ node server3.js
gpsData Array : [ [ { imei: '86851212020143921',
device_info: 0,
device_info_new: 0,
seconds: 0,
gps_time: 1548760740,
sys_time: 1548760744,
heart_time: 1548760744,
server_time: 1548760748,
lng: 33.756899,
lat: -13.973598,
course: 160,
speed: 7,
status: '010000fb000000000000000000000000',
location: 'GPS',
acc: '1',
acc_seconds: 335,
voice_status: -1,
voice_gid: 0 } ] ]
showing that it's working
how can I make this code into an asynchronous WebSocket that continuously gets that data, then stores it in MongoDB with given fields?
ok so I found a solution, the best(in my opinion) way is to use setInterval() function, put the HTTP request inside the function to set how many times per unit time you want to insert in the db, then from there mongodb accepts objects by default, so if you return an object to mongodb is will save it for you, here's the code
MongoClient.connect('mongodb://127.0.0.1:27017/gpsapp2', function(err,client){
if(err) return console.log(err)
db = client.db('gpsapp2')
let counter =0
setInterval(()=>{
http.get(_url2, res =>{
let body='';
res.on("data", data =>{
body+=data;
})
res.on("end",()=>{
body = JSON.parse(body);
//console.log(counter++,'Records inserteerd')
db.collection('gpsdata').save(body.data[0]);
})
})
},1000);
http.get from the url, parse the body then save to collection. dont forget the API call is asynchronous so any call for the data outside res.on('end') will get empty or undefined results.
hope this helps somebody.
I want to use javascript fetch to post data to Node.js backend. I use fetch on the javascript side in angular 2 functions.
In my front end I have button to save data to array:
<input #data /><button (click)="addGoal(data.value)">Add</button>
<ul><li *ngFor="let goal of goals">{{goal}}</li></ul>
<br/><button (click)="saveData()">Save</button>
Angular 2 side i add data into array goals and call angular 2 function addGoal from the front end:
export class AppComponent {
title = 'Goals';
goals = [];
addGoal(goal:string) {
this.goals.push(goal);
}
saveData() {
fetch("http://localhost:3000/", {
method: "POST",
mode:"no-cors",
body: {goals: this.goals},
});
}
}
I want to get data to backend to later save it to the database.
Node.js side:
var data = {};
app.post('/',function (req,res) {
data = req.body;
})
app.get('/', function (req, res) {
res.send(data);
})
However, this is not a correct solution. Can you help me?
edit: Body.fetch functions(https://developer.mozilla.org/en-US/docs/Web/API/Body) not seem to work.
In case you are using express, you need to use the body-parser middleware. If you are dealing with html5 FormData/multiplart formdata, you need multer.