Skip to content Skip to sidebar Skip to footer

Post Action Api With Object Parameter Within The Url

I've got an API where some of the parameters need to be given within the URL. Example of how my api url looks like: https://www.server.com/api/actions/execute?auth_type=apikey&

Solution 1:

If you need to pass parameters via URL you should use GET, if you use POST then the parameters should be passed in the body

Solution 2:

First install the package axios from the url https://www.npmjs.com/package/react-native-axios Then create two service for handling get and post request so that you can reuse them

GetService.js

import axios from'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

exportconstGetService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.get(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}    

PostService.js

import axios from'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

exportconstPostService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.post(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}

Sample code for using get and post services is given below

import { PostService } from'./PostService';
import { GetService } from'./GetService';


let uploadData = newFormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });let jwtKey = ''; // Authentication key can be added herePostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});



GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});

Post a Comment for "Post Action Api With Object Parameter Within The Url"