Failed to retrieve data with axios get from a date (Reactjs) - javascript

I need to retrieve data based on a date. I tested my route with Postman and everything works fine. However, when I do my axios query with a date, it returns an empty array. I understood that it would be a date format problem with axios, but I couldn't solve it. Could you help me please?
Here is my code in the front:
const getDailyWorking =()=>{
let datas={
activity_creationTimestamp: ('2022-06-28'),
user_id:1
}
console.log(datas)
return axios.get(config.api_url+'/dailyWork', datas).then((response)=>{
console.log(response.data)
}).catch((err)=>{
console.log(err)
})
}

You're using the wrong type of request. A GET request can't include a body in the request, while a POST request can include a body in the request. Maybe you should check the documentation again and get the parameters sorted.

You can specify the GET parameters like this axios.get('/path', { params: datas } which is equivalent to axios.get('/path?activity_creationTimestamp=2022-06-28&user_id=1')
. Otherwise, provide more information about the server side route.

Related

How to use GraphQL response as a variable in Javascript

I am new to GraphQL and I am have the query working as expected but I am having trouble working with the response.
Query
query {
all_assets(where: {title: "suppliestile-blt9607aa6a28539d2e.zip"}) {
items {
url
}
}
}
Calling Response
var jsondata = JSON.stringify(response.data);
console.log(jsondata);
This is giving me the following response
{"data":{"all_assets":{"items":[{"url":"https://assets.contentstack.io/v3/assets/blt15ad871ba49b8a41/blta52af33b959c061f/6352b5fb3bd922566d8d3f2d/suppliestile-blt9607aa6a28539d2e.zip"}]}}}
Essentially I would like to use the url value as a variable moving forward but I am having trouble extracting it from all of the nested objects and arrays does anyone have any advice to get me pointed in the right direction?
The answer won't differ because it's a Graphql request. It's just a response that you get through the request via response.data.
If you need to access specific object/property within the response , you need to use the index of the object, you can do
const url = response.data.all_assets.items[0].url;

Problem with React making Get request to Node(express)

As the title says, i have a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:
So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"
async handleClickLicencia (event) {
event.preventDefault();
console.log(this.state);
console.log("licenciaInput: "+this.state.licenciaInput);
const datoBuscar = this.state.licenciaInput;
axios.get('http://localhost:3001/atletas/:licencia',this.state)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error)
})
And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:
const getAtletasByLicencia = (request, response) => {
const licencia = request.body.licenciaInput;
console.log("Request: "+request);
console.log("what the server gets: "+licencia);
// const licencia = request.licenciaInput;
const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
pool.query(sentencia, (error, results) =>{
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.
TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work
I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance
EDIT: Im also adding this code that i have which shows the route for my method in the server:
app.get('/atletas/:licencia', db.getAtletasByLicencia)
As #Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client
Change your request to:
axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
...
and your route (if you are using express) should look like this:
app.get('/atletas/:licencia', function (req, res) {
var licencia = req.params.licencia
...
})
As you are using request.body you should send a POST request with axios and add a body.

Use axios GET as axios POST in ReactJS

A friend has an API with a GET.
I would like to know if I can send data to a lambda with a get, as if I were using a simple POST.
I have this
await axios.post(
' ENDPOINT_API',
{
resultat_net_N1:`${resultat_net_N1_form}, ${resultat_net_N1}, ${resultat_net_N1_form_1}, ${resultat_net_N1_1}`,
resultat_net_N: `${resultat_net_N_form}, ${resultat_net_N}, ${resultat_net_N_form_1}, ${resultat_net_N_1}`,
},
);
I’d like a GET that behaves like this piece of code. I don't know if it's possible. Thanks in advance.
There are workarounds, but they aren't suggested, POST SHOULD BE TO POST, and GET SHOULD BE TO GET
const res = await axios.get("/ENDPOINT_API",
{ data: {
resultat_net_N1: resultat_net_N1 }
}
)
I suggest sending them as params
const res = await axios.get("/ENDPOINT_API",
{ params: {
resultat_net_N1: resultat_net_N1 }
}
)
It all depends on the use case you are sending the data. The Get method is exposing the data as query parameters and as the name suggest it is used for getting data from the API. POST method is not exposing the data like get and is used for sending data to the API in its request body. If you try to send sensitive data it is really not recommended to use get. You can find basic difference between the http methods and their usage here

POSTing using ReactJS, Superagent and Python (flask)

I'm trying to post some data to a Python backend that i made with Flask. I'm using SuperAgent in a React component. For some reason i keep getting HTTP error 400.
I've read many posts about similar problems using JQuery and flask. The solution there is to set the contentType the same way i have and also JSON.stringify the data. I've tried stringify but it doesn't change anything. Still getting an HTTP 400.
Any ideas?
JS code:
request.post(link)
.set('Content-Type', 'application/json; charset=utf-8')
.send({tag: 'tag1', comment: 'Cool'})
.end(function(err, res){
console.log(res);
});
Python function/endpoint:
#app.route('/api/leavecomments', methods=['POST'])
def comment_to_photos():
comment = request.form['comment']
print(comment)
tag = request.form['tag']
...
So the issue for anybody else that has this problem, they need to use method named get_json which will have the values being passed to it in JSON format. In the case of the code above it was looking for those values as a query string post parameters, which is typically sent via form posts. In the case of an AJAX JSON post, the data exists inside the request.body.
For more information check out...
http://flask.pocoo.org/docs/0.10/api/#flask.Request.get_json

Parse.com getting data from callback URL

I'm currently trying to use an API and for the API, the developer console of that app asks the developer to submit a callback URL. Whenever the user of the app does something, it submits a GET request to the callback URL and I can retrieve data from that request. The current url I am using is https://appId:javascript-key=myJavascriptKey#api.parse.com/1/functions/receiveInfo. How can I handle the data, a.k.a the GET parameters, from the GET request? I found an answer on Parse.com that says how to retrieve data from a POST request, but all it says is that data = request.body. Do I do the same for GET requests and if so what do I do after that? Is request.body a json value?
Parse.Cloud.define("receiveInfo", function(request,response){
var params = request.body;//is this right to get the GET parameters they send? if so what do I do next?
});
The documentation has your solution at: https://parse.com/docs/cloud_code_guide#functions
For GET requests you have to use the request.params object which has all your request parameters for a GET are there. POSTS are sent in the request body, GET in the request parameters.
It looks like you are trying to get the params you can use something similar to:
Parse.Cloud.define("myMethod", function(request, response) {
if(request.params.myparam == "moo") {
response.success("Cow!");
}
else {
response.error("Unknown type of animal");
}
});

Categories