I was attempting to send payload
, and URLSearchParams
through an API
URL from my react-native
application. I initialized an axios
instance as,
JavaScript
x
11
11
1
import { BASE_URL } from '../../utils/constants';
2
const axios = require('axios');
3
4
const api = axios.create({
5
baseURL: BASE_URL,
6
timeout: REQUEST_TIMEOUT,
7
headers: {
8
'content-type': 'application/json',
9
},
10
});
11
And from another component, I imported the axios
instance, then,
JavaScript
1
14
14
1
import api from "../../utils/api"
2
import { API_URL } from '../../utils/constants';
3
4
requestAPI(userId, sessionId){
5
let data = { "userId": userId, "sessionId": sessionId };
6
7
api
8
.post(API_URL, data)
9
.then(response => {
10
// handle the response
11
// do stuffs
12
})
13
}
14
The payload
contains the request body for the API. As stated in API docs, I have to send the filters through URLSearchParams
, like,
JavaScript
1
6
1
api
2
.post(API_URL?status=success&type=out, data)
3
.then(response => . {
4
//handle the response and stuffs
5
});
6
Any suggestions on how to send the URLSearchParams
without hardcoding or just appending search queries to the API_URL
? TIA.
Advertisement
Answer
Use a new URL()
and assign the URLSearchParams() to the search
property of the URL object.
You can then pass that object directly to axios
JavaScript
1
20
20
1
const API_URL ='https://httpbin.org/get',
2
REQ_URL = new URL(API_URL);
3
4
const data = Object.entries({'foo':'bar', age:23}),
5
params = new URLSearchParams(data);
6
7
// to manually add params
8
params.append('username', 'foobar');
9
10
REQ_URL.search = params;
11
12
13
// example passing url object to fetch()
14
(async ()=>{
15
console.log('REQ_URL :', REQ_URL)
16
const req= await fetch(REQ_URL);
17
const {args, url} = await req.json();
18
console.log('URL from response:',url)
19
console.log(args)
20
})()