How to assign headers in axios.all method React Native - reactjs

I'm getting data from multiple api's and rendering into <Pickers /> but the issue is that I'm unable to assign headers for Auth in this axios.all method. Kindly provide me a solution or mistake if I'm doing.
axios.all([
axios.get(this.apiUrl + '/case/GetCaseType'),
axios.get(this.apiUrl + '/case/GetCasePriority')
], { headers: { 'authorization': 'bearer ' + this.state.jwtToken } })
.then(axios.spread(( response2, response3) => {
console.log('Response 1: ', response1.data.retrn);
console.log('Response 2: ', response2.data.retrn);
console.log('Response 3: ', response3.data.retrn);
this.hideLoader();
})).catch(error => console.log(error.response));

You can create a service file to handle all request for GET or POST, FIle for handling GET request with Autherization header is given belwo
GetService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const GetService = (data,Path,jwtKey) => {
// jwtKey is null then get request will be send without header, ie for public urls
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.get(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}

You can use the configs and create instance to set common things like url, token, timeout etc
import axios from 'axios';
const http = axios.create({
baseURL: this.url,
timeout: 5000
});
http.defaults.headers.common['authorization'] = `bearer ${this.state.jwtToken}`
export async function yourAPIcallMethod(){
try{
const [res1,res2] = await http.all([getOneThing(), getOtherThing()]);
//when all responses arrive then below will run
//res1.data and res2.data will have your returned data
console.log(res1.data, res2.data)
//i will simply return them
return {One: res1.data, Two: res2.data}
}
catch(error){
console.error(error.message || "your message")
}
}
This can be used in your component.jsx like
import {yourAPIcallMethod} from './httpService';
async componentDidMount(){
const data = await yourAPIcallMethod();
this.setState({One: data.One, Two: data.Two})
}
You can see and learn more on github axios.

Related

how to pass token to local storage with axios

I created an Axios instance to set up the baseURL and the headers. The header also needs to contain the token for authorization.
export const instance = axios.create({
baseURL: import.meta.env.VITE_API_URL,
headers: {
Authorization: `Bearer ${localStorage.getItem(LOCAL_STORAGE_API_KEY)}`
},
validateStatus: () => true
});
when the user logs in, I call an API to get some data related to the user using useQuery. When I log in, I try to store the token in local storage, but I think I'm doing something wrong and I get an error from the backend.
export const LOCAL_STORAGE_API_KEY = 'token';
import { instance } from './ApiProvider';
import { LOCAL_STORAGE_API_KEY } from '#/helpers/constants';
export const loginActions = async ({ email, password }) => {
const response = instance
.post('/api/v1/Auth/Login', {
user: {
email: email,
password: password
}
})
.then((data) => {
instance.defaults.headers.post[
'Authorization'
] = `Bearer ${localStorage.getItem('LOCAL_STORAGE_API_KEY')}`;
return data;
});
return response;
};
The problem is that instance is created before you have the auth header value available and hence on subsequent call it will pass the value as undefined.
You can use axios interceptors for this task.
instance.interceptors.request.use(
function(config) {
const token = localStorage.getItem("LOCAL_STORAGE_API_KEY");
if (token) {
config.headers["Authorization"] = 'Bearer ' + token;
}
return config;
},
function(error) {
return Promise.reject(error);
}
);

How to properly set axios default headers

I'm using reactjs for my project but I have one issue, in config.js file where i set my global axios configurations, I'm setting default headers for axios requests but when i make axios request it does not send those headers in requests.
config.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'URL/api'
});
export const setAuthToken = (token) => {
if (token) {
// Apply to every request
instance.defaults.headers.common['Authorization'] = 'Bearer ' + token;
} else {
// Delete auth header
delete instance.defaults.headers.common['Authorization'];
}
};
export default instance;
Login.js
import axios from '../../../config';
import { setAuthToken } from '../../../config';
axios
.post('/auth/signin', {
username: email,
password: password
})
.then((res) => {
setCurrentUser(res.data);
setAuthToken(res.data.accessToken);
setLoading(false);
})
.catch((err) => {
console.log(err);
setLoading(false);
setError(true);
});
You can use axios interceptors for this task.
1-) Inside the successfull login, put the retrieved token to the localStorage. Remove setAuthToken line.
.then((res) => {
setCurrentUser(res.data);
localStorage.setItem("token", res.data.accessToken);
setLoading(false);
})
2-) Add this interceptor to your axios instance.
const instance = axios.create({
baseURL: 'URL/api'
});
instance.interceptors.request.use(
function(config) {
const token = localStorage.getItem("token");
if (token) {
config.headers["Authorization"] = 'Bearer ' + token;
}
return config;
},
function(error) {
return Promise.reject(error);
}
);
I had to create the header object structure within the instance for global header overriding to work:
The code snippet below does not working (but it does not raise any error); global header is used when using the instance:
// Index.js
axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
// myAxios.js
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
instance.defaults.headers.common['Authorization'] = 'AUTH_TOKEN_FROM_INSTANCE';
This does work, instance header overrides the global default:
// Index.js
axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
// myAxios.js
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
headers: {
common: {
Authorization: 'AUTH_TOKEN_FROM_INSTANCE'
}
}
});
It seems to me that this object structure should be created by default when using #create.
===========================================================================
Additionally, if you want to unset the header don't use delete. Here's a test:
it('should remove default headers when config indicates', function (done) {
var instance = axios.create();
instance.defaults.headers.common['Content-Type'] = 'application/json';
instance.post('/foo/bar/', {
firstName: 'foo',
lastName: 'bar'
}, {
headers: {
'Content-Type': null
}
});
getAjaxRequest().then(function (request) {
testHeaderValue(request.requestHeaders, 'Content-Type', null);
done();
});
});
You can add axios headers token by default..Just follow 2 steps
#Step - #1.
Create axios instance -
const API_BASE_URL = "http://127.0.0.1:8000/api";
export const axiosPrivate = axios.create({
baseURL: API_BASE_URL,
timeout: 60000
});
#Step - #2.
Set default header before sent api request
axiosPrivate.interceptors.request.use((request) => {
// Do something before request is sent
request.headers = {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
};
return request;
}, (error) => Promise.reject(error));

axios.post returns bad request of 400 React Native

I'm getting my token from an API but unfortunately my API is returning 400 bad request. I've already checked my api via Postman and it's working fine there. Kindly let me know solution or any mistake.
async componentWillMount(){
axios.post('http://api.myapiurl.com/token', {
grant_type: 'PASSWORD',
username: 'MY_USERNAME',
password: 'MY_PASSWORD'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(response => {
console.log(response.data)
}).catch(err => console.log("api Erorr: ", err.message))
}
error in response below
Request failed with status code 400
- node_modules\axios\lib\core\createError.js:16:24 in createError
- node_modules\axios\lib\core\settle.js:18:6 in settle
- ... 10 more stack frames from framework internals
It is Solved by using QueryString.stringify(). I just pass the body into QueryString.stringify() like below:
axios.post('http://api.apiurl.com/token', QueryString.stringify({
grant_type: 'MY_GRANT_TYPE',
username: 'MY_USERNAME',
password: 'MY_PASSWORD'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}).then(response => {
console.log(response.data)
}).catch(err => console.log("api Erorr: ", err.response))
From what I can see you are sending json data, but your Content-Type header is set to application/x-www-form-urlencoded; charset=UTF-8. if your api is expecting json then it should be application/json.
try using fetch instead, might be some axios bug, you dont need to add any libraries, here is an example:
fetch("http://api.myapiurl.com/token", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
grant_type: "PASSWORD",
username: "MY_USERNAME",
password: "MY_PASSWORD"
})
})
.then(res => {
res.json();
})
.then(data => console.log(data)) // ur data is here
.catch(err => console.log("api Erorr: ", err));
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'
}
};
export const GetService = (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'
}
};
export const PostService = (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 = new FormData();
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 here
PostService(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
});
Reference from one of my another post Post action API with object parameter within the URL
If you have any doubts, feel free to know

axios post request to send form data

axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload contains data. What am I doing wrong?
Axios POST Request:
var body = {
userName: 'Fred',
userEmail: 'Flintstone#gmail.com'
}
axios({
method: 'post',
url: '/addUser',
data: body
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Browser Response:
If I set headers as:
headers:{
Content-Type:'multipart/form-data'
}
The request throws the error
Error in posting multipart/form-data. Content-Type header is missing boundary
If I make the same request in postman it's working fine and sets values to my POJO class.
Can anyone explain how to set boundary or how can I send form data using axios.
You can post axios data by using FormData() like:
var bodyFormData = new FormData();
And then add the fields to the form you want to send:
bodyFormData.append('userName', 'Fred');
If you are uploading images, you may want to use .append
bodyFormData.append('image', imageFile);
And then you can use axios post method (You can amend it accordingly)
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Related GitHub issue:
Can't get a .post with 'Content-Type': 'multipart/form-data' to work # axios/axios
In my case I had to add the boundary to the header like the following:
const form = new FormData();
form.append(item.name, fs.createReadStream(pathToFile));
const response = await axios({
method: 'post',
url: 'http://www.yourserver.com/upload',
data: form,
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`,
},
});
This solution is also useful if you're working with React Native.
Check out querystring.
You can use it as follows:
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
Upload (multiple) binary files
Node.js
Things become complicated when you want to post files via multipart/form-data, especially multiple binary files. Below is a working example:
const FormData = require('form-data')
const fs = require('fs')
const path = require('path')
const formData = new FormData()
formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, {
headers: formData.getHeaders()
})
Instead of headers: {'Content-Type': 'multipart/form-data' } I prefer headers: formData.getHeaders()
I use async and await above, you can change them to plain Promise statements if you don't like them
In order to add your own headers, you just headers: { ...yourHeaders, ...formData.getHeaders() }
Newly added content below:
Browser
Browser's FormData is different from the NPM package 'form-data'. The following code works for me in browser:
HTML:
<input type="file" id="image" accept="image/png"/>
JavaScript:
const formData = new FormData()
// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')
// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
2020 ES6 way of doing
Having the form in html I binded in data like so:
DATA:
form: {
name: 'Joan Cap de porc',
email: 'fake#email.com',
phone: 2323,
query: 'cap d\ou'
file: null,
legal: false
},
onSubmit:
async submitForm() {
const formData = new FormData()
Object.keys(this.form).forEach((key) => {
formData.append(key, this.form[key])
})
try {
await this.$axios.post('/ajax/contact/contact-us', formData)
this.$emit('formSent')
} catch (err) {
this.errors.push('form_error')
}
}
Using application/x-www-form-urlencoded format in axios
By default, axios serializes JavaScript objects to JSON. To send data
in the application/x-www-form-urlencoded format instead, you can use
one of the following options.
Browser
In a browser, you can use the URLSearchParams API as follows:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).
Alternatively, you can encode data using the qs library:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
Or in another way (ES6),
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url, };
axios(options);
Even More straightforward:
axios.post('/addUser',{
userName: 'Fred',
userEmail: 'Flintstone#gmail.com'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
import axios from "axios";
import qs from "qs";
const url = "https://yourapplicationbaseurl/api/user/authenticate";
let data = {
Email: "testuser#gmail.com",
Password: "Admin#123"
};
let options = {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
data: qs.stringify(data),
url
};
axios(options)
.then(res => {
console.log("yeh we have", res.data);
})
.catch(er => {
console.log("no data sorry ", er);
});
};
I had the similar issues when using FormData with axios to make calls on https://apps.dev.microsoft.com service and it error-red out with "The request body must contain the following parameter: 'grant_type'"
After reformatting the data from
{
grant_type: 'client_credentials',
id: '123',
secret: '456789'
}
to
"grant_type=client_credentials&id=123&secret=456789"
and the following code worked:
const config: AxiosRequestConfig = {
method: 'post',
url: https://apps.dev.microsoft.com/auth,
data: 'grant_type=client_credentials&id=123&secret=456789',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
i needed to calculate the content length aswell
const formHeaders = form.getHeaders();
formHeaders["Content-Length"] = form.getLengthSync()
const config = {headers: formHeaders}
return axios.post(url, form, config)
.then(res => {
console.log(`form uploaded`)
})
A boundary (which is used, by the server, to parse the payload) is set when the request is sent. You can't obtain the boundary before making the request. So, a better way to get this is using getBoundary() from your FormData.
var formData = new FormData();
formData.append('userName', 'Fred');
formData.append('file0', fileZero);
formData.append('file1', fileOne);
axios({
method: "post",
url: "myurl",
data: formData,
headers: {
'Content-Type': `multipart/form-data; ${formData.getBoundary()}`,
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
I needed to upload many files at once using axios and I struggled for a while because of the FormData API:
// const instance = axios.create(config);
let fd = new FormData();
for (const img of images) { // images is an array of File Object
fd.append('images', img, img.name); // multiple upload
}
const response = await instance({
method: 'post',
url: '/upload/',
data: fd
})
I did NOT specify the content-type: multipart/form-data header!
The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT
packageData: (data) => {
const form = new FormData()
for ( const key in data ) {
form.append(key, data[key]);
}
return form
}
Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following
packageData: (obj, form, namespace) => {
for(const property in obj) {
// if form is passed in through recursion assign otherwise create new
const formData = form || new FormData()
let formKey
if(obj.hasOwnProperty(property)) {
if(namespace) {
formKey = namespace + '[' + property + ']';
} else {
formKey = property;
}
// if the property is an object, but not a File, use recursion.
if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
packageData(obj[property], formData, property);
} else {
// if it's a string or a File
formData.append(formKey, obj[property]);
}
}
}
return formData;
}
For me it worked using axios, typescript and form-data(v4.0.0):
import FormData from "form-data";
import axios from "axios";
async function login() {
var data = new FormData();
data.append("User", "asdf");
const return = await axios.post(
"https://ptsv2.com/t/1q9gx-1652805776/post", data,
{ headers: data.getHeaders() }
);
console.log(return);
}
This should work well when needing to POST x-www-form-urlencoded data using axios from a NodeJS environment. You may need to add an Authorization header to the config.headers object if the endpoint requires authentication.
const config = {
headers: {
accept: 'application/json',
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded'
}
const params = new URLSearchParams({key1: value1, key2: value2});
return axios
.post(url, params.toString(), config)
.then((response) => {
return response.data;
})
.catch((error) => console.error(error));
In my case, the problem was that the format of the FormData append operation needed the additional "options" parameter filling in to define the filename thus:
var formData = new FormData();
formData.append(fieldName, fileBuffer, {filename: originalName});
I'm seeing a lot of complaints that axios is broken, but in fact the root cause is not using form-data properly. My versions are:
"axios": "^0.21.1",
"form-data": "^3.0.0",
On the receiving end I am processing this with multer, and the original problem was that the file array was not being filled - I was always getting back a request with no files parsed from the stream.
In addition, it was necessary to pass the form-data header set in the axios request:
const response = await axios.post(getBackendURL() + '/api/Documents/' + userId + '/createDocument', formData, {
headers: formData.getHeaders()
});
My entire function looks like this:
async function uploadDocumentTransaction(userId, fileBuffer, fieldName, originalName) {
var formData = new FormData();
formData.append(fieldName, fileBuffer, {filename: originalName});
try {
const response = await axios.post(
getBackendURL() + '/api/Documents/' + userId + '/createDocument',
formData,
{
headers: formData.getHeaders()
}
);
return response;
} catch (err) {
// error handling
}
}
The value of the "fieldName" is not significant, unless you have some receiving end processing that needs it.
https://www.npmjs.com/package/axios
Its Working
// "content-type": "application/x-www-form-urlencoded",
// commit this
import axios from 'axios';
let requestData = {
username : "abc#gmail.cm",
password: "123456"
};
const url = "Your Url Paste Here";
let options = {
method: "POST",
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + "your token Paste Here",
},
data: JSON.stringify(requestData),
url
};
axios(options)
.then(response => {
console.log("K_____ res :- ", response);
console.log("K_____ res status:- ", response.status);
})
.catch(error => {
console.log("K_____ error :- ", error);
});
fetch request
fetch(url, {
method: 'POST',
body: JSON.stringify(requestPayload),
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + token,
},
})
// .then((response) => response.json()) . // commit out this part if response body is empty
.then((json) => {
console.log("response :- ", json);
}).catch((error)=>{
console.log("Api call error ", error.message);
alert(error.message);
});
transformRequest: [
function(data, headers) {
headers["Content-Type"] = "application/json";
return JSON.stringify(data);
}
]
try this, it works

Sending the bearer token with axios

In my react app i am using axios to perform the REST api requests.
But it's unable to send the Authorization header with the request.
Here is my code:
tokenPayload() {
let config = {
headers: {
'Authorization': 'Bearer ' + validToken()
}
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
config
)
.then( ( response ) => {
console.log( response )
} )
.catch()
}
Here the validToken() method would simply return the token from browser storage.
All requests are having a 500 error response saying that
The token could not be parsed from the request
from the back-end.
How to send the authorization header with each requests? Would you recommend any other module with react?
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.
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.
You can create config once and use it everywhere.
const instance = axios.create({
baseURL: 'https://example.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
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
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);
}
);
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)
});
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)
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",
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 });
};
// 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;
})
If you are sending a post request with empty data remember to always set the second parameter to either empty object or empty string just as in the example below. e.g: axios.post('your-end-point-url-here', '', config)
if you don't set it axios will assume that whatever you are passing as the second parameter is a formData
const config = {
headers: { Authorization: `Bearer ${storage.getToken()}` }
};
axios
.post('http://localhost:8000/api/v1/get_token_payloads', {}, config)
.then(({ data: isData }) => {
console.log(isData);
})
.catch(error => {
console.log(error);
});
You must mention the 2nd parameter body for the post request even if it is empty, try this :
tokenPayload() {
let config = {
headers: {
'Authorization': 'Bearer ' + validToken()
}
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
// empty body
{},
config
)
.then( (response) => {
console.log(response)
} )
.catch()
}
You can try configuring the header like this:
const headers = {"Content-Type": "text/plain", "x-access-token": token}
You can use interceptors in axios:
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
More on that you can find here: https://axios-http.com/docs/interceptors
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")
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

Resources