All requests through one function, which adds accessToken itself - javascript

I don't want to repeat headers for all request.
async function fetchA() {
return await axios({
method: 'GET',
url: API_URL + `/api/a`,
headers: {'Authorization': 'Bearer ' + localStorage.getItem(ACCESS_TOKEN)}
});
}
async function fetchAById(id) {
return await axios({
method: 'GET',
url: API_URL + `/api/a/${id}`,
headers: {'Authorization': 'Bearer ' + localStorage.getItem(ACCESS_TOKEN)}
});
}
I assigned headers to const but in this case accessToken was null.
What is best way to create function which adds accessToken itself?

function getHeaders() {
const serviceInstance = axios.create({
url: API_URL + `/api/a`,
headers: {'Authorization': 'Bearer ' + localStorage.getItem(ACCESS_TOKEN)}
});
return serviceInstance;
}
async function fetchA() {
return await getHeaders().get(url)
});
}
I hope this may help.

Related

Why is axios not returning correctly

I am trying to replace a fetch with axios. I keep getting undefined in my console log.
async componentDidMount() {
console.log('app mounted');
const tokenString = sessionStorage.getItem("token");
const token = JSON.parse(tokenString);
let headers = new Headers({
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token
});
const response = await axios({
method: 'get',
url: Config.apiUrl + `/api/Orders/GetAllInvoices`,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token }
});
console.log(`axios: ${response.json}`)
this.setState({ invoiceList: response.json });
//const response = await fetch(Config.apiUrl + `/api/Orders/GetAllInvoices`, {
// method: "GET",
// headers: headers
//});
//const json = await response.json();
//console.log(json);
//this.setState({ invoiceList: json });
...
... the commented out fetch is working. I just now added the .json even though axios should not need it. Neither way works. What am I doing wrong?
Did you even console.log(response) just to see whats inside of it?
I guess you dont, because response is an object witch has no json key in it. You should use response.data

Query for Spotify's Web API Client Credentials Flow

I'm trying to make a http request based on the documentation at https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow Client Credentials Flow.
I've written
const BASE_URL = 'https://accounts.spotify.com/api/token';
fetch(BASE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64(clientID) + ':' + base64(clientSecret)
},
body: JSON.stringify({'grant_type:client_credentials'})
})
Does this follow what it says to do? I'm confused how to write the body of the post request.
What I ended up doing which works:
async authorize(){
let myHeaders = new Headers();
myHeaders.append("Authorization", `Basic ${my_clientID:clientSecret}`);
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
}
let res = await fetch("https://accounts.spotify.com/api/token", requestOptions);
res = await res.json();
return res.access_token;
}
async search(){
const access_token = await this.authorize();
this.setState({access_token});
const BASE_URL = 'https://api.spotify.com/v1/search';
let FETCH_URL = `${BASE_URL}?q=${this.state.query}&type=artist&limit=1`;
const ALBUM_URL = 'https://api.spotify.com/v1/artists';
let myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);
const requestOptions = {
method: 'GET',
headers: myHeaders
}
let res = await fetch(FETCH_URL, requestOptions);
res = await res.json();
console.log("ARTIST", res);
}
From the link you have shared, the client credential flow is a client (server-side) that makes a request to the spotify API server. Thus, it is a server-to-server authentication flow (not authorization). You are using the fecth API which is client-side so that means that your implementation should be server-side. If you are using a node.js runtime server-side framework, just look up the http.request API to make a request server-side.
For example, this would be a pure node.js implementation:
const options = {
hostname: 'https://accounts.spotify.com/api/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64(clientID) + ':' + base64(clientSecret)
}
};
const req = http.request(options, (res) => {
res.setEncoding('utf8');
// process the data bit by bit or in chunks...
res.on('data', (chunk) => {});
// ...and do something with it when there is no more data in response
res.on('end', () => {
console.log('No more data in response.');
});
});
// handle the error explicitly
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();
For me, I'm not sure if this is the case for anyone else, but the spotify api was refusing base64(clientID) + ":" + base64(clientKey), but accepting base64(clientID + ":" + clientKey)

Axios - Dynamic Header not working. Why does my code not work when i set the variable dynamically but does when i hard code it?

I can't seem to figure out how to get my 2nd http post to work "queuecallback". It looks like the problem is specific to how i set the headers. Headers = my_headers. It works when i hard code it but not when i try to call it dynamically. Any help would be greatly appreciated. Thanks!
const axios = require('axios');
const queuecallback = require('axios');
var my_token;
var my_formated_token;
var my_headers;
var myJSON;
function connectToAgentHandler(agent) {
axios({
method: 'post',
url: 'https://myapi.com/AuthorizationServer/Token',
data: {
username: 'myusername',
password: 'mypassword',
grant_type: 'password'
},
headers: {'Authorization': 'basic 123456789Aghtiaqq111kkksksksk111'}
}
)
.then((result) => {
my_token = result.data.access_token;
console.log("Token:", my_token);
my_formated_token = 'bearer ' + my_token;
console.log("Formated Token:", my_formated_token);
var my_headers = "{'Authorization': '" + my_formated_token + "'}";
console.log("My Headers:", my_headers);
});
//lets execute the callback from an agent
queuecallback({
method: 'post',
url: 'https://myapi.com/go',
data: {
phoneNumber: '1111111111',
skill: '12345'
},
headers: my_headers
}
)
.then((result) => {
console.log("your contactId is:", result.data.contactId);
});
}
});
It's not necesseray to require two axios :
const axios = require('axios');
const queuecallback = require('axios');
Your problem is that you set the headers in the first call
var my_headers = "{'Authorization': '" + my_formated_token + "'}";
axios is a asynchronous function so the queuecallback is called directly after the first axios call (which is not finished). You can use async function to "wait" the end of the first call :
const axios = require('axios');
async function connectToAgentHandler(agent) {
try {
let result = await axios({
method: 'post',
url: 'https://myapi.com/AuthorizationServer/Token',
data: {
username: 'myusername',
password: 'mypassword',
grant_type: 'password'
},
headers: {
'Authorization': 'basic 123456789Aghtiaqq111kkksksksk111'
}
});
const token = `bearer ${result.data.access_token}`;
const headers = {
'Authorization': token
};
result = axios({
method: 'post',
url: 'https://myapi.com/go',
data: {
phoneNumber: '1111111111',
skill: '12345'
},
headers
});
console.log("your contactId is:", result.data.contactId);
} catch (err) {
// process error
}
};

CYPRESS store cy.request response in a variable

I have this one file that calls a login function
testing.js
var res = accounts.createSession(config.email_prod,config.password_prod,user_id)
on another file, I have this:
accounts.js
export function createSession(email,password,user_id){
cy.request({
method:'POST',
url:config.accounts_prod + '/token',
headers:{
'authorization': 'Basic testestestestest'
},
qs:{
'grant_type':'password',
'username':email,
'password':password
}
}).then((response)=>{
var X = response.body.access_token
cy.log("create session " + x)
login(response.body.access_token, user_id)
})
}
export function login(token,user_id){
var result = cy.request({
method:'POST',
url:config.ws_prod + '/login.pl',
headers:{
'authorization': token,
'Content-Type' : 'application/x-www-form-urlencoded'
},
body:'user_id='+user_id+'&device_id='+device_id+'&os_type='+os_type
})
return token
}
so I want to store token value and return it to res variable on testing.js file
but everytime I store token (in this example I store it inside X) and I try to print it, it always says undefined
but I can do cy.log(token) and it was fine on login() function, but that's all it can do, it cannot be store into a variable
is there another way for me to store token ?
Maybe if i use a callback like parameter, then the second function will wait for the asynchronous task is over
export function createSession(email,password,user_id,callback){
cy.request({
method:'POST',
url:config.accounts_prod + '/token',
headers:{
'authorization': 'Basic testestestestest'
},
qs:{
'grant_type':'password',
'username':email,
'password':password
}
}).then((response)=>{
var X = response.body.access_token
cy.log("create session " + x)
callback(response.body.access_token, user_id);
})
}
var login = function (token,user_id) {
var result = cy.request({
method:'POST',
url:config.ws_prod + '/login.pl',
headers:{
'authorization': token,
'Content-Type' : 'application/x-www-form-urlencoded'
},
body:'user_id='+user_id+'&device_id='+device_id+'&os_type='+os_type
})
return token
}
// then call first fn
createSession(email,password,user_id,login);
I had almost the same issue. Comment on this answer helped me
// testing.js
let res = null;
before(() => {
accounts.createSession(config.email_prod, config.password_prod, user_id).then((responseToken) => {
res = responseToken;
console.log('response token', responseToken);
});
});
it('My tests ...', () => {
console.log('...where I can use my session token', res);
});
// accounts.js
export function createSession(email, password, user_id) {
cy.request({
method: 'POST',
url: config.accounts_prod + '/token',
headers: {
'authorization': 'Basic testestestestest'
},
qs: {
'grant_type': 'password',
'username': email,
'password': password
}
}).then((response) => {
var x = response.body.access_token
cy.log("create session " + x)
login(response.body.access_token, user_id)
return response.body.access_token; // needs return statement
})
}

Sending authorization token with Axios GET does not work

I am making a GET request in my react native app. My code is:
const config = {
headers: {
Authorization: `Bearer ${authToken}`,
},
};
axios.get(url, config);
The authorization token is not being sent along with the request. How do I send it?
You could use the same GET method in two ways.
Method 1
axios.get(your_url, {
headers: {
Authorization: 'Bearer ' + your_token
}
})
Method 2
axios({
method: 'get',
url: your_url,
headers: {
Authorization: 'Bearer ' + your_token
}
})
For POST method
axios({
method: 'post',
url: your_url,
data: { "user_id": 1 }
headers: {
Authorization: 'Bearer ' + your_token
}
})
Please try with the any of above method and let me know.
try this:
var req = {
url: the url ,
method: "get",
headers: {
Authorization: "Bearer " + val,
Accept: "application/json"
}
};
axios(req)
.then(response=>{console.log(response)})
.catch(error => {});
});

Categories