Passing parameters in get query to vue js? - javascript

I do the filtering, when I click on the apply filter, the query in the API flies away
php-developer, says that the request should be get, not post
how to pass parameters to the get query?
example for my post request
export const filterDate = (options) => {
console.log(options)
return axios.post(url, options).then(({ data }) => {
if (data.errors) throw new Error(JSON.stringify(data.errors));
return data;
})
};
but if I just replace the post on the get parameters are not transferred

If you want to pass parameters in get request, pass an object with "params" property, as follow:
axios.get('/user', {
params: {
ID: 12345
}
});

in options you specify a param object:
params: {
k: val
},
or by building an UrlSearchParam object:
const params = new URLSearchParams();
params.append('k', 'val');
axios.get(url, params);

Related

Making request parameter optional in axios get request

I have below axios request.
import axios from 'axios';
axios.get('/user', {
params: {
ID
Name
}
})
.then(function (response) {
console.log(response);
})
I want all the request parameter should be optional. if user send ID then it should give ID, if user enter ID and Name it should consider both. If user enters none it should display all the record.
I dont know how to handle this in react.
think u are looking for something like below:
params: {
...(ID && {
ID: ID
}) // conditional spread operator
}
You would evaluate the params in a variable based on a condition before giving them to axios:
const parameters = condition ? {ID: id, Name: name} : {};
axios.get('/user', {
params: parameters
})
.then(function (response) {
console.log(response);
})

How to building a fetch call to pass value to a method that expects an Object?

I currently not sure how to use a fetch post call to pass an object to a method expecting that object. I created a payload and passed it but does not seem to work. I have set a breakpoint in the code behind but it is never hit. Not sure why the fetch call is not working. Any suggestions on way the endpoint is not being reached?
This is my method in C#.
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword(Player player){
{
Javascript:
const continueBtn = document.getElementById("continueBtn");
continueBtn.onclick = () => {
const email = document.getElementById("lblEmail").innerHTML;
sendResetEmail(email);
}
async function sendResetEmail(email) {
const payload = {
email: email
}
const data = new FormData();
data.append("json", JSON.stringify(payload));
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
body: data
});
}
if you don't want to provide the name of the parameter in your client, you need to give the [FromBody] attribute in your API:
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword([FromBody] Player player){
}
Then, on the client, there are multiple ways, but the most common/modern is to use JSON encoding:
const payload = {
email: email
}
const data = JSON.stringify(payload);
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});
}

how to write one GET api call using axios instance with and without params in React JS

I am new to React JS and Axios. I want to understand the best way of creating a GET instance using Axios that works with and without params. I am have developed a sample REST API call from React using axios.create({}) as below and it works fine.
import axios from 'axios';
const instance = axios.create({
baseURL: 'example.com'
});
export default {
getAllData: (url) =>
instance({
'method': 'GET',
'url': url
})
}
My requirement is to create axios GET instance that works with and without params and I could achieve it like below by creating 2 different functions:
export default {
getAllData: (url) =>
instance({
'method': 'GET',
'url': url
}),
getUser: (url, userId) =>
instance({
'method': 'GET',
'url': url,
'params' : userId
})
}
Is there any way to create one GET function that works with and without params using Axios in React JS?
You can do something like this:
getUser: (url, userId) =>
instance({
'method': 'GET',
'url': url,
...(userId && {'params' : userId})
})
If userId exists, it will append the {'params': userId} object to the current one.
You don't have to create 2 different methods. If you don't pass the userId parameter, it will be null and won't be passed to the API call.
You can use this code:
import axios from 'axios';
// Set Global default
axios.defaults.baseURL = 'example.com';
const getData = (url, userId) => axios(url, userId);
export default getData;
You can call with userId:
getData('/user', userId);
Or without:
getData('/user');
This is how you can do it:
export default {
getUser: (url, userId) =>
instance.get(url, {
...(userId && {'params' : userId})
})
}
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})

How to pass a query param in post call in Reactjs

I am new to reactjs.I am doing a post call but not sure, how to pass a boolean value in url as a query param in reactjs. For eg: http://www.abx.com?example=true. How do I pass this example in post api call.
Endpoint: API_SAMPLE: "/sample",
post call:
postCall() {
const config = {
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
product: {
body
},
};
return http
.post(this.API.API_SAMPLE, data, config)
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
i want to add a boolean value in my query param, how will i do that
You can use template literals to pass the variable to your URL.
const example = true;
const url = `http://abx.com/sample?example=${example}`
or use it this way:
return http.post(`${this.API.API_SAMPLE}?example=${example}`, data, config) {...}
wether you are using POST or GET you will have to modify the URL.
You can do this "dynamically" or you can use something like URLSearchParams:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var URL = "http://example.com/search";
var searchParams = new URLSearchParams(URL);
searchParams.append("example", "true");
searchParams.toString() // "http://example.com/search?example=true";
Just make sure you support the correct browsers:
https://caniuse.com/#search=urlsearchparams

Can't intercept and manipulate data with Axios [duplicate]

I am using axios in my Express API and I want to transform the payload before sending it off to another API. axios has just the thing for this called transformRequest. This is where I ran into issues though.
The code I have looks like:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
const encryptedString = encryptPayload(JSON.stringify(data));
data = {
SecretStuff: encryptedString,
};
return data;
},
],
});
// firing off my request using the instance above:
const postData = {
id: 1,
name: 'James',
};
instance.post('/getStuff', postData)
and ultimately, I want to post api-url.com the JSON: {"SecretStuff": "some-base64-string"} - not the postData object shown above.
From the docs, it says: "The last function in the array must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream" - but of course here I am returning an object, data. Oddly enough in the axios docs it shows them returning data from transformRequest, but in their case that must be the correct data type.
How do I actually transform a payload with axios?
axios.create({
transformRequest: [(data, headers) => {
// modify data here
return data;
}, ...axios.defaults.transformRequest]
});
have to append the original axios.defaults.transformRequest to the transformRequest option here..
Wouldn't you want to JSON.stringify() your transformed post data? Like below:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
const encryptedString = encryptPayload(JSON.stringify(data));
data = {
SecretStuff: encryptedString,
};
return JSON.stringify(data);
},
],
});
To amend the values instead of override the output in the request I would do this:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
data.append('myKey','myValue');
return data;
},
]
});
Here's what worked for me in TypeScript, inspired by the concat solution from Phil here: https://stackoverflow.com/a/70949237/2339352
The goal here was to use the humps library to convert to/from a snake case Python API:
this.axios = axios.create({
transformResponse: (data: any) => {
return humps.camelizeKeys(JSON.parse(data))
},
transformRequest: [(data: any) => {
return humps.decamelizeKeys(data);
}].concat(axios.defaults.transformRequest ? axios.defaults.transformRequest : [])
});

Categories

Resources