Use axios GET as axios POST in ReactJS - javascript

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

Related

How to get single value from request response

I started writing a program that will automate user actions, by now it's meant to be an easier menu to make faster actions by just sending requests to the official website by clicks on my own page. (something like web-bot but not exactly).
My problem is when i send login request in response i get back user_id, server, session_id etc. And I need to save that session_id to make the other actions.
How can i save this to variable.
All in JavaScript.
I was looking in the internet since yesterday for an answer and i still can't find (or understand) how to get this
I tried
function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })
//There's the problem to solve
.then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id);
// I even tried the substring but 1. It won't work as I want because There are sometimes //more and less letters. 2. I get and error "Cannot read properties of undefined (reading //'substr')"
`session = obj;
session_id = session.substring(291,30)
console.log(session_id)`
It looks like you're using the text() method on the Response object returned from fetch(), which will give you a string representation of the response.
You probably want to be using the json() method instead, and from that you can get your session_id.
This guide has some more useful information that may help you: https://javascript.info/fetch
Ok it works now with
`async function login(){ let session = await fetch('url', {
//code
}
let result = await session.json();
console.log(result);
session_id = result.data.user.session_id;
user_id = result.data.user.id;`

Access query parameters using axios

I am using React in the frontend and Django in the backend and I am currently doing the API integration for which I am using Axios.
So in the frontend side I am calling a URL like this
http://localhost:3000/attempt/?quiz_id=6
and I want the quiz_id = 6 so that I can use this afterward to access data in the backend.
I am using Functional components if that helps.
You can take a look at axios's documentation in github
If what you want to do is a GET request this should be enough:
axios.get('http://localhost:3000/attempt/?quiz_id=6')
.then((res) => {
// handle success
console.log(res);
})
Also you have available this kind of usage:
axios.get('http://localhost:3000/attempt', {
params: {
quiz_id: 6
}
}).then((res) => {
// handle success
console.log(res);
});
You can use this too:
const data = await axios.get('http://localhost:3000/attempt/?quiz_id=6').then(res => res.data);
You can include dynamic quiz_id by using params. The way for this is to making an axios request using the id of the param that you want to update and return:
Your code will read like so:
axios.get('http://localhost:3000/attempt/${quiz_id}', quiz_id);

Receive raw response data using axios

I am trying to receive the raw response data, not the response headers or body. As an example, an image here shows the tab where this data is found:
Now, I am trying to receive this data when making an HTTP Request using `Axios`. Is this even possible?
I have tried searching online for about 2 hours, as this was a huge problem I was facing. I tried other sites, including stack overflow, to get the correct answer. If possible, could you please answer my question if you know? Thanks in advance.
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r)
})
}
I'm pretty sure you must access the data property in the response object r. Also - since you are using the reddit API - make sure you are providing api_type in the request url (api_type=json for instance):
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?api_type=json&user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r.data)
return r.data;
})
}
For anyone reading this: Just to clarify, the api_type parameter in the request url is specific to the reddit API and most likely won't work any other API.

Is it possible to send delete/put requests to a Azure AD secured api or get jwt Token as String using aadHttpClientFactory

I have a custom Api which I secured with Azure AD like the following tutorial:
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient
Thats working great.
now I have the following Code to make a GET request to my custom API (working):
this.context.aadHttpClientFactory
.getClient('MY_API_URL')
.then((client: AadHttpClient) => {
console.log(AadHttpClient.configurations.v1);
return client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1
);
})
.then(response => {
var res= response.json();
return res;
}).then( (res: any[]) => {
...
HERE I WOULD LIKE TO GET MY TOKEN
});
So this is working how I expect it to work.
But the aadHttpClientFactory only supports GET and POST requests
Now my Idea was to just make some PUT/DELETE requests with jQuery and use the Bearer token I got above (tested with postman and its working).
But then I realised, that I won't get the token that easy.
When I console.log(AadHttpClient.configurations.v1) I only get this:
Sure I could just change my API to use POST instead of PUT/DELETE but that would be pretty ugly
Does anyone has an Idea on how I could get the token as a String to do custom requests with it?
AadHttpClient supports the fetch(url, configuration, options) method, where options can include all of the request configuration options supported by the Fetch API.
So, to make a DELETE request, you would do something along the lines of:
client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1,
{
method: 'DELETE'
}
);
I solved it now.
Maybe my answer will help someone later.
according to philippe Signoret's answer the is the fetch() function.
I had to use it like following:
this.context.aadHttpClientFactory
.getClient(api_url)
.then((client: AadHttpClient) => {
return client
.fetch(
MY_URL,
AadHttpClient.configurations.v1,
{
method: METHOD, //put/DELETE etc.
headers: [
["Content-Type", "application/json"]
],
body: JSON.stringify({
YOUR REQUEST BODY
})
}
)
});

Axios POST params show empty on server - using MERN stack

I want to update a document in Mongo, but when I send an Axios POST request to the server with params for the updates I receive nothing but a blank object on the server side - I'm using Node.js with an Express server (MERN stack).
I have tried the qs library module and Node's querystring module. I tried including headers with
'Content-Type': 'application/x-www-form-urlencoded' and 'application/json'.
My Axios POST request:
const A = 1;
const B = 2;
const data = { A, B };
console.log(qs.stringify(data)); // A=1&B=2
axios.post(url('upVote'), qs.stringify(data));
The server route:
app.post('/upVote', async (req, res) => {
console.log(req.params); // {}
await DB.updateVote(ID, collection, voteCount);
res.end();
});
The headers as shown by Chrome's DevTools.
... Also, all my axios.get() requests work fine and grab data from Mongo and send it back to my app properly, and the url/endpoints match.
There are a couple of ways to send data to the server with axios.
I see the confusion with the documentation in axios, I have not seen this usage before and it does seem to be broken upon looking at the request logs and object.
1) axios.post receives body of the request as a second parameter. So if you want to pass parameters to axios, you should do something like this:
const B = 2;
const data = { A: 1, B: 1 };
axios.post(url('upVote'), {}, { params: data });
Note that axios will handle stringification on it's own and that the third parameter is a config object.
On the server the params will be available at request.query
2) If you want to stringify the parameters yourself, then you should append them into your URL like so
axios.post(`url('upVote')?${qs.stringify(data)}`);
Same here, data on the server will be under request.query
3) It's generally better to use the body of the post request to transfer large data payloads for convenience. You should also consider what your caching strategies are and if they rely on request url without the consideration of request body it may be a concern.
axios.post(url('upVote'), data);
In this case data on the server will be under request.body
UPD: Originally forgot to mention that you will need a body-parser middleware to access request.body.
4) You can use axios without method shorthands which may be useful for some people
axios({
method: 'POST',
url: url('upVote'),
params: data
})
This is identical to the example in 1.
And all of them return a Promise which you can .then().catch() or await.
I think you want .body instead of .params.As you are sending data in body by post using axios. You are printing params which will print nothing for this url/api .
Try
console.log(req.body) // instead of req.params
If this did not work then please show us your react code.
Moreover
In react you have to add .then() after axios else it will say unhanded promise
To get params on server side you have to make some changes
In axios (react)
axios.post(url('upVote/param'), qs.stringify(data));
In server
app.post('/upVote/:params', async (req, res) => {
console.log(req.params)
.....
})
I think you are calling res.end(). I think it should be res.send(...)
This answer should help: https://stackoverflow.com/a/29555444/1971378

Categories