score:-2
axios
by itself comes with two useful "methods" the interceptors
that are none but middlewares between the request and the response. so if on each request you want to send the token. use the interceptor.request
.
i made apackage that helps you out:
$ npm i axios-es6-class
now you can use axios as class
export class userapi extends api {
constructor (config) {
super(config);
// this middleware is been called right before the http request is made.
this.interceptors.request.use(param => {
return {
...param,
defaults: {
headers: {
...param.headers,
"authorization": `bearer ${this.gettoken()}`
},
}
}
});
this.login = this.login.bind(this);
this.getsome = this.getsome.bind(this);
}
login (credentials) {
return this.post("/end-point", {...credentials})
.then(response => this.settoken(response.data))
.catch(this.error);
}
getsome () {
return this.get("/end-point")
.then(this.success)
.catch(this.error);
}
}
i mean the implementation of the middleware
depends on you, or if you prefer to create your own axios-es6-class
https://medium.com/@enetoolveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a
it is the medium post where it came from
score:-2
there are a lot of good solution but i use this
let token=localstorage.getitem("token");
var myaxios=axios.create({
baseurl: 'https://localhost:5001',
timeout: 700,
headers: {'authorization': `bearer ${token}`}
});
export default myaxios;
then i import myaxios to my file and
myaxios.get("sth")
score:0
// usetoken is hook i mad it
export const usetoken = () => {
return json.parse(localstorage.getitem('user')).token || ''
}
const token = usetoken();
const axiosintance = axios.create({
baseurl: api,
headers: {
'authorization':`bearer ${token}`
}
});
axiosintance.interceptors.request.use((req) => {
if(token){
req.headers.authorization = `bearer ${token}`;
}
return req;
})
score:4
i use a separate file to init axios instance and at the same time, i add intercepters to it. then in each call, the intercepter will add the token to the request header for me.
import axios from 'axios';
import { gettoken } from '../hooks/usetoken';
const axiosinstance = axios.create({
baseurl: process.env.react_app_base_url,
});
axiosinstance.interceptors.request.use(
(config) => {
const token = gettoken();
const auth = token ? `bearer ${token}` : '';
config.headers.common['authorization'] = auth;
return config;
},
(error) => promise.reject(error),
);
export default axiosinstance;
here is how i use it in the service file.
import { canceltoken } from 'axios';
import { toolresponse } from '../types/tool';
import axiosinstance from './axios';
export const gettools = (canceltoken: canceltoken): promise<toolresponse> => {
return axiosinstance.get('tool', { canceltoken });
};
score:9
just in case someone faced the same issue.
the issue here is when passing the header without data, the header's configuration will be in the payload data, so i needed to pass null instead of data then set the header's configuration.
const config = {
headers: {
"content-type": "application/json",
"authorization": `bearer ${cookies.get("jwt")}`,
},
};
axios.get(`${base_url}`, null, config)
score:10
this works and i need to set the token only once in my app.js
:
axios.defaults.headers.common = {
'authorization': 'bearer ' + token
};
then i can make requests in my components without setting the header again.
"axios": "^0.19.0",
score:15
if you want to some data after passing token in header so that try this code
const api = 'your api';
const token = json.parse(sessionstorage.getitem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"authorization" : `bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
console.log(error)
});
score:29
by using axios interceptor:
const service = axios.create({
timeout: 20000 // request timeout
});
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
config.headers["authorization"] = "bearer " + gettoken();
return config;
},
error => {
promise.reject(error);
}
);
score:32
the second parameter of axios.post
is data
(not config
). config
is the third parameter. please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config
score:49
you can create config once and use it everywhere.
const instance = axios.create({
baseurl: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'authorization': 'bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
score:147
here is a unique way of setting authorization token in axios. setting configuration to every axios call is not a good idea and you can change the default authorization token by:
import axios from 'axios';
axios.defaults.baseurl = 'http://localhost:1010/'
axios.defaults.headers.common = {'authorization': `bearer ${token}`}
export default axios;
some api require bearer to be written as bearer, so you can do:
axios.defaults.headers.common = {'authorization': `bearer ${token}`}
now you don't need to set configuration to every api call. now authorization token is set to every axios call.
score:298
const config = {
headers: { authorization: `bearer ${token}` }
};
const bodyparameters = {
key: "value"
};
axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
bodyparameters,
config
).then(console.log).catch(console.log);
the first parameter is the url.
the second is the json body that will be sent along your request.
the third parameter are the headers (among other things). which is json as well.
Source: stackoverflow.com
Related Query
- Sending the bearer token with axios
- issue with the Authorisation: Bearer access_token (the headers) in Axios POST in reacts
- Want to send JWT token in headers along with data using axios but getting this error : Cannot set headers after they are sent to the client
- post request in Axios with 400 or 401 - bearer token
- How to pass Header JWT Token with Axios & React?
- What are the differences between Redux-Thunk and Redux-Promise when used with Axios apis?
- Sending requests to Elasticsearch with axios
- What is the best way to make multiple get request with axios in a loop?
- Making 2 sequential requests with Axios - second request depends on the response of 1st
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- React Native + Expo + Axios file upload not working because axios is not sending the form data to the server
- Configuring CORS with express and making requests on the front end with axios
- how to properly replace axios api with fetch api and map over the received data in nodeJS?
- Get the access token in localStorage generated by MSAL.JS and put it in Axios
- react, redux with typescript error: Type '{}' is missing the following properties from type 'IProps': email, token
- ReactJs - Fetch a quote every 5 seconds with axios and display it in the <p>
- Axios baseURL is not appending with the URL in react.js
- Can't get request a link with Axios due to No 'Access-Control-Allow-Origin' header is present on the requested resource
- issue with sending headers in post request to the API
- Sending a MSAL token to backend using Axios
- React axios with PHP Rest API , how to write the baseurl
- Sending POST request with body in axios
- Axios with firebase does not return the data while putting it
- How to set cookie with JWT token in ReactJS frontend using Node, Express, Axios
- axios , login with api , handle token
- Input undefined when sending post request to the nodejs api using react and axios
- How to send axios put request with jwt token in reactjs
- What is the correct way to pass a token to axios from React?
- Starting a php session from react with an axios call does not keep the session alive, but doing it with postman works just fine
- how to save the data from firebase I recently Created with axios and react?
More Query from same tag
- filter object by two nested values
- create-react-app is working only with cmd but not with bash. With bash : 'npx' not recognized as an internal or external command
- In React, why is a called function containing a closure not immediately run upon component mount?
- How to solve type issue when implementing React children components to have only specific components?
- Repeated calls to react-typist using React.js
- reactjs router - setup a login page
- babel-preset-react-app not picking up environment variables
- Typescript 3.7.2, React and Material UI 4.5.1 Snackbars - trying to do an error popup but get styles errors
- React - customers.map is not a function
- Check if react element is empty
- Testing dispatched actions in Redux thunk with Jest
- How to prevent useEffect re-rendering twice
- How to extend React component class created via React.createClass
- Rendering array pictures from calling API in react.js
- How to solve issue in jest unit test?
- Recharts - pass array of values to Line component
- why action.payload use in reactjs
- React MUI Formik Input loses focus after typing
- Styled components nested rules don't work
- Convert render() of class component to functional component in react js
- Ant Design's maskClosable modal property is not working?
- Redirect page upon login using react-router-v5 and redux-toolkit
- How to extract JSON data fetched from API and pass into react-plotly?
- React renders blank svg images
- Empty password input value on autocomplete (React.js)
- Cant get createSlider from @typeform/embed to work in React
- React Intro tutorial: how do list's keys get their value?
- Cannot convert undefined or null to object : Next.js || React
- Cannot read properties of undefined (reading 'slice')
- To call dispatch function in react