Access query parameters using axios - javascript

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);

Related

How can I understand the use of query parameter in REST api?

As a learner, I am trying to call the rest api. For example, you can see and copy the url from api provider as they listed on that link page.
https://docs.api.jikan.moe/#tag/top/operation/getTopAnime
function App() {
const [topAnime, SetTopAnime] = useState([]);
useEffect(() => {
fetch(`https://api.jikan.moe/v4/top/anime`)
.then((response) => response.json())
.then((data) => {
console.log(data);
SetTopAnime(data);
})
.catch((err) => {
console.log(err.message);
});
}, []);
But the question is; this does not let me to call a specific data I want to call.
To do that, I need to add some query parameters as api page written for developer.
Now, I see several examples that someone set it as follows:
const getData = () => {
axios
**.get(`${apiTop}?sfw=true&limit=20`)**
.then((res) => {
return setData(res.data.data);
})
.catch((error) => {
console.log(error);
});
};
that .get method and following code makes sense. But how that developer who coded that line knew '?sfw=true&' such thing?
If I don't understand this; what topic could be the one I should review then? I believe I understand what promises and fetch are, but not sure focusing on 'query parameter' is the right thing to solve my problem.
tl;dr
To call a specific data from getTopAnime, how should I set query parameters? (with my understanding, https://api.jikan.moe/v4/top/anime/type/movie
or
https://api.jikan.moe/v4/top/anime?=query/type/movie
is the limit to expand the thoughts.
Thanks...
From the documentation of the API -- https://docs.api.jikan.moe/
There must be API documentation where you can read about these URI structures.
Though a real REST service sends you hyperlinks with URIs or URI templates which you follow, so you need to know what type of hyperlink watch for and the service gives you the URI structure. This is called HATEOAS constraint.

Route that is executed within another route in Node.js is not being executed

Good Evening,
I have a function that contains a route that is a call to the Auth0 API and contains the updated data that was sent from the client. The function runs, but the app.patch() does not seem to run and I am not sure what I am missing.
function updateUser(val) {
app.patch(`https://${process.env.AUTH0_BASE_URL}/api/v2/users/${val.id}`,(res) => {
console.log(val);
res.header('Authorization: Bearer <insert token>)
res.json(val);
})
app.post('/updateuser', (req, ) => {
const val = req.body;
updateUser(val);
})
app.patch() does NOT send an outgoing request to another server. Instead, it registers a listener for incoming PATCH requests. It does not appear from your comments that that is what you want to do.
To send a PATCH request to another server, you need to use a library that is designed for sending http requests. There's a low level library built into the nodejs http module which you could use an http.request() to construct a PATCH request with, but it's generally a lot easier to use a higher level library such as any of them listed here.
My favorite in that list is the got() library, but many in that list are popular and used widely.
Using the got() library, you would send a PATCH request like this:
const got = require('got');
const options = {
headers: {Authorization: `Bearer ${someToken}`},
body: someData
};
const url = `https://${process.env.AUTH0_BASE_URL}/api/v2/users/${val.id}`;
got.patch(url, options).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
Note: The PATCH request needs body data (the same that a POST needs body data)

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

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
})
}
)
});

Node.js require JSON from web address?

I am trying to load JSON data from https://blockchain.info/ticker into Node like so: const btc = require(https://blockchain.info/ticker) Obviously, this does not work. How can one do this?
You can't pass require() a URL. It needs a filename.
If you want to load some JSON from a remote server, you can use the request or request-promise packages. The loading will be asynchronous though so you will need to use the result in the appropriate callback. Here's an example:
const rp = require('request-promise');
rp({json: true}, "https://blockchain.info/ticker").then(data => {
// use data here
console.log(data);
}).catch(err => {
// process error here
console.log(err);
});

Categories