Tuesday 8 June 2021

React - CORS issue, Axios API call in one place to entire app, Service componet DI , component - 3 ways

 React - Axios call - hooks based - 3 types API connection - CORS issue fix

===========================================================================

cmd:>npx create-react-app reactProject


cd reactProject


....


develop some pages/component/screens in react projects

.....


reactProject:> npm i Axios


verify the axios version at package.json


Avoid the cors issue in local development, while prod - both UI and service need to be in same place.

package.json

-----------------


"proxy": "http://localhost:8080",

"engines": {

"node": "^12",

"npm": "^6"

},


Best - Method:1


src/utils/api.js

----------------------


import axios from 'axios';



const call = method => (url, { body, query, headers } = {}) => {

return axios({

method,

baseURL: url, //baseURL: `http://localhost:8080${url}`,

data: body,

headers, //headers:{"Access-Control-Allow-Origin": "*"},

params: query

})

.then(response => response.data)

.catch(function(error) {

console.log(error);

});

};


export default {

get: call('GET'),

post: call('POST'),

put: call('PUT'),

delete: call('DELETE')

};




App.js

-------

useEffect( () =>{

// global get,post,put methos, just pass end point url of API, Error handling done in one place.


const userData = api.get('/api/endpoint');

console.log(userData)

});




Method:2

----------


src/services/serviceApi.js

---------------------------

import axios from 'axios';


class ServiceApi {


getUserData() {

return axios.get('/api/endPoint').catch(function(error) {

console.log(error);

});

}


getUserInfoData() {

return axios.get('/api/user').catch(function(error) {

console.log(error);

});

}

}



export default new ServiceApi()



App.js

------

import ServiceApi from '../services/serviceApi';


useEffect( () =>{

ServiceApi.getUserData().then(res => {

console.log(res.data.data);

//setData(res.data.data[0]);

})


});


Method:3

--------

component.ts

-------------


import axios from 'axios'; // method:3


useEffect( () =>{

axios.get('/api/endpoint').then ( response =>{

console.log(response)

}).catch( function(error){

console.log(error)

});

},[])

No comments:

Post a Comment