Expected query string:
http://fqdn/page?categoryID=1&categoryID=2
Axios get request:
fetchNumbers () {
return axios.get(globalConfig.CATS_URL, {
params: {
...(this.category ? { categoryId: this.category } : {})
}
})
.then((resp) => {
// console.log(resp)
})
.catch((err) => {
console.log(err)
})
}
As you can see, it works perfectly with just 1 value for 1 parameter, but if i wanted to make multiple values - it doesn't work, i've tried to use an array:
...(this.category ? { categoryId: [1, 2] } : {})
But it returns this way:
http://fqdn/page?categoryID[]=1&categoryID[]=2
So it just not working. Had a look at this issue: Passing an object with a parameter with multiple values as a query string in a GET using axios
But can't figure out, how he solved this problem.
You can use Axios's paramsSerializer to customize the serialization of parameters in the request.
Note that URLSearchParams serializes array data the way you're expecting:
const searchParams = new URLSearchParams();
searchParams.append('foo', 1);
searchParams.append('foo', 2);
console.log(searchParams.toString()); // foo=1&foo=2
So you could use that class in paramsSerializer as follows:
// my-axios.js
export default axios.create({
paramsSerializer(params) {
const searchParams = new URLSearchParams();
for (const key of Object.keys(params)) {
const param = params[key];
if (Array.isArray(param)) {
for (const p of param) {
searchParams.append(key, p);
}
} else {
searchParams.append(key, param);
}
}
return searchParams.toString();
}
});
// Foo.vue
import axios from './my-axios.js';
export default {
methods: {
async send() {
const { data } = await axios({
url: '//httpbin.org/get',
params: {
categoryId: [1, 2, 3]
}
});
// ...
}
}
}
demo
This is not an axios related issue. It depends on whether your backend service is able to understand query params in this fashion(seems to be framework dependent). From your question, I think it is not working when queryParams like following are sent
?categoryID[]=1&categoryID[]=2
and it expects
?categoryID = 1,2
What you can do is transform array to such string before passing it to params in axios. Update the following piece in your code and it should solve your problem.
...(this.category ? { categoryId: this.category.join(',') } : {})
Take a look at following thread
How to pass an array within a query string?
Related
Im start learning vue.js and ive got some troubles. I need to use dictionary analog in js. Its called map. but i dont know where i should define it. I need to use it in checkDevices() method and in HTML code
P.S. Sorry for my English
export default {
data: () => ({
}),
devicesList: new map(
"varNameOne", false,
"varNameTwo", false,
"varNameThree", false,
),
methods: {
async checkDevices () {
let response = await axios.get(`/some/api`)
console.log("res.data: ", response.data);
devicesList.forEach((values, keys) => {
console.log("Key: ", keys, "Value: ", values);
})
}
}
}
ive trying to define it before export default like this: let devicesList = new map(...);, but it doesnt work.
In axios.get(`/some/api`) ive got response frome server with data (response.data):
device1: true
device2: false
device1: true
I need take it frome response in key-value pair for using in UI like
device1 connected
device2 disconnected
divice3 connected
I don't know the JSON of your Axios response so you need to update checkDevices function to match the key values. there is no need to use map above export default. you can do this in mounted function.
export default {
data:function(){
return {
devicesList:[]
}
},
mounted:function(){
this.devicesList = new Map();
this.devicesList.set('device1', false);
this.devicesList.set('device2', false);
this.devicesList.set('device3', false);
},
methods: {
async checkDevices () {
let response = await axios.get(`/some/api`)
console.log("res.data: ", response.data);
devicesList.forEach((values, keys) => {
console.log("Key: ", keys, "Value: ", values);
//Please Use YOUR RESPONSE.data here to update the device List
})
}
}
}
I am trying to dynamically build an axios get request, and have currently hardcoded some values in my parameters array to test with like so:
const parameters = [
'table=cumulative',
'where=koi_disposition like \'CANDIDATE\' and koi_period>300 and koi_prad<2',
'order=koi_period',
'format=json'
];
let searchParameters = '';
const api = axios.create({
baseURL: 'https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI'
});
for (let element in parameters) {
if (element !== '') {
searchParameters += `?${parameters[element]}`;
}
}
I then add this query to my axios get request below:
export const getExoplanets = async () => {
try {
searchParameters = searchParameters.replace(/;/g, "");
console.log(`${searchParameters}`);
return await api.get(`${searchParameters}`);
// return await api.get(`?table=cumulative&where=koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2&order=koi_period&format=json`);
} catch (error) {
return error;
}
};
When the variable version runs the api returns the error:
ERROR
Error Type: UserError
Message: Constraint contains an illegal keyword: ";"
However when the commented out, hard coded version runs it works just fine. At some point an extra semicolon is being added to the request. I assume it is being added at the end, but I can't find where or how. Any ideas how to fix this?
Axios supports easy query parameters using the params config option.
Just provide an object of key / value pairs and Axios will do all the encoding for you
const params = {
table: "cumulative",
where: "koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2",
order: "koi_period",
format: "json"
}
return api.get("", { params })
// or return api.get("", { params: params })
This will send a request to
?table=cumulative&where=koi_disposition+like+%27CANDIDATE%27+and+koi_period%3E300+and+koi_prad%3C2&order=koi_period&format=json
it seem you having an issue in this bellow line you have used the \ rest of this you can wrap all the things in the double quote.
'where=koi_disposition like \'CANDIDATE\' and koi_period>300 and koi_prad<2',
"where=koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2",
I'm working with an existing backend which I can not adjust anymore. I need to do a call which gets all messages. One of the params is type, this can be used to get all messages from a specific type. The backend developer had told me I had to use this multiple times looking like this:
/api/message?type=test&type=test2
So i tried sending it as a array, which resulted in:
/api/message?type[]=test&type[]=test2
Finding some information on SO made me use QS but this also doesn't give me the result I need
api/message?type%5B0%5D=test&type%5B1%5D=test2
export const getMessages = () =>
baseApi
.get('/message', {
params: {
type: [
'test',
'test2'
]
},
paramsSerializer: (params) => {
return qs.stringify(params)
}
})
.then((r) => r.data as Message[])
This isn't related to Axios. The qs library is responsible for generating that string. See its documentation:
When arrays are stringified, by default they are given explicit
indices:
qs.stringify({ a: ['b', 'c', 'd'] });
// 'a[0]=b&a[1]=c&a[2]=d'
You may override this by setting the indices option to false:
qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
// 'a=b&a=c&a=d'
You can use the append method. Like (URLSearchParams):
const params = new URLSearchParams()
params.append("type","test")
params.append("type","test2")
Then, you set the params in the request just like you did:
export const getMessages = () =>
baseApi
.get('/message', {
params: {
params
},
paramsSerializer: (params) => {
return qs.stringify(params)
}
})
.then((r) => r.data as Message[])
I'm trying to concatenate all the query params string that I have into a one final query including all params but I keep getting this result :
_filter=0=((startDate=ge=2019-09-30T22:00:00.000Z);(endDate=le=2019-10-
03T22:00:00.000Z));1=
(category=eq=Warning,category=eq=Error);&_limit=50&_sort=asc
with the annoying 0=, 1=, 2=, ....
The expected result is to be like that :
_filter=((startDate=ge=2019-10-06T12:39:05.000Z;endDate=le=2019-10-
07T23:59:59.999Z);(category=eq=ALERT,category=eq=META))"
Here is my code:
generateQueryString(obj: any) {
let query = [];
if (obj.startDate && obj.endDate) {
query = query.concat(this.buildDateQueryString(obj.startDate, obj.endDate)
);
}
if (obj.category) {
query = query.concat(this.buildCategoryQueryString(obj.category));
}
return query;
}
Let us assume you want pass some data like
const userData = {
firstName: 'Arpit',
lastName: 'Patel'
}
You can pass this object into Query Params like this.
this.router.navigate(['/dashboard/details'], { queryParams: { user: JSON.stringify(userData) } });
Then extract this Object in next component which is called as below.
this.route.queryParams.subscribe(params => {
const user= JSON.parse(params.user);
console.log(user);
});
This will result in JSON object. You can access it directly.
I am having a lot of trouble scanning and then using FilterExpression to filter based on a single value. I have looked at the api documentation and other stack overflow questions, but am still having trouble figuring the proper syntax for this. Since I am also using react and javascript for the first time, this may be a problem with my understanding of those.
Below is what I am trying to use as a filter expression. uploadId is the field name in the Dynamo database table and event.pathParameters.id is the variable that should resolve to the value that the scan results are filtered on.
FilterExpression: "uploadId = :event.pathParameters.id"
Below is the code in within context:
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
export async function main(event, context, callback) {
const params = {
TableName: "uploads",
FilterExpression: "uploadId = :event.pathParameters.id"
};
try {
const result = await dynamoDbLib.call("scan", params);
if (result.Item) {
// Return the retrieved item
callback(null, success(result.Item));
} else {
callback(null, failure({ status: false, error: "Item not found." }));
}
} catch (e) {
callback(null, failure({ status: false }));
}
}
Thank you for your help!
Always use Expression with ExpressionAttributeValues. params should look like this.
const params = {
TableName: "uploads",
FilterExpression: "uploadId = :uid",
ExpressionAttributeValues: {
":uid" : {S: event.pathParameters.id} //DynamoDB Attribute Value structure. S refer to String, N refer to Number, etc..
}
};