How can use AsyncStorage in string template - javascript

//await is not working in string template is there any other way to use AsyncStorage
export const http = new HttpService(BASE_URL, {
'Content-Type': 'application/json',
Authorization: `Bearer ${await AsyncStorage.getItem('userToken')}`,
})
And without await promise is not resolved how can I fix this please help

The most straightforward way I see is to simply use a variable to first get the token from AsyncStorage and then use it in your request. Hence, your code would be something like: -
const token = await AsyncStorage.getItem('userToken');
const http = new new HttpService(BASE_URL, {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
})
You might also have to make a function, something like: -
const request = async () => {
const token = await AsyncStorage.getItem('userToken');
const http = new HttpService(BASE_URL, {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
});
}

Related

How To Solve "Expected type object but found type string" in REST API calls? (reactjs, javascript)

I'm trying to use following Auth0 API call: https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id
const sUserMetadata = async () => {
const domain = "xxxxxxxxxxxxxxx"
try {
const accessToken = await getAccessTokenSilently({
audience: `${domain}/api/v2/`,
scope: "update:current_user_metadata",
});
const userDetailsByIdUrl = `${domain}/api/v2/users/${user.sub}`;
const metadataResponse = await fetch(userDetailsByIdUrl, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${accessToken}`,
},
body: { "email_verified": true }
})
let user_metadata = await metadataResponse;
console.log(user_metadata)
} catch (e) {
console.log(e.message);
}
};
sUserMetadata().then(r => null);
I am receiving following response error:
{"statusCode":400,"error":"Bad Request","message":"Payload validation error: 'Expected type object but found type string'.","errorCode":"invalid_body"}
Obviously the Body-Tag provides it in the correct form with Bracets {} so it Should! be an Object.
I have tried:
JSON.parse()
I have tried to add Content-Type which results in a freaking "SYNTAX ERROR" because of the - in content-type which doesnt make any sense because under chrome debugger I can obviously see that there is a property called content-type: text/plain;charset=UTF-8 and I have no idea how else I am supposed to change this?
headers: {
Authorization: `Bearer ${accessToken}`,
Content-Type: 'application/json',
},
Putting Content-Type inside Apostrophes 'Content-Type' so it doesn't give a Syntax Error and then you using JSON.Stringify() at the Body-Tag part fixes the problem.
const metadataResponse = await fetch(userDetailsByIdUrl, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ "user_metadata" : { "addresses": {"work_address": "100 Industrial Way"} }}),
})
PS: save me from javascript pls

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

How can I connect to a API using fetch and bearer token?

I would like to connect to REST API that uses a token Bearer.
I try the JS code below :
sessionStorage.setItem('MCToken',
JSON.stringify('123456')
);
let datastructuresAPI = () => {
let token = JSON.parse(sessionStorage.getItem('MCToken'));
let header = new Headers({
'Cache-Control': 'no-cache',
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
});
let response = fetch('https://mon_url',{
method: 'POST',
headers: header,
body:JSON.stringify({
"methodName":"connect",
'grant_type': 'client_credentials',
"serviceName":"ConnectionService"
}),
'x-frame': 'same-origin',
mode: 'no-cors'
});
console.log(response)
}
datastructuresAPI();
But I can’t connect, I have these message (the first is the result of the console.log)
Thank you for your help
Fetch function is an async function and you should wait it.
fetch(...)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
For the other result (401) are you sure that your REST API waits token with Bearer {token}? It could be only {token}.

How to add "Bearer" another route headers after user logged in?

I'm new to programming and I'm currently working on a small project.
I'm trying to implement some authorization using JWT.
I've watched a few videos online and found that most people have the "Bearer" + access token in their headers.
I've gone through a few posts and I found that I needed to add the authorization "Bearer" myself but I'm not quite sure how to get there.
Can I please get some help?
Here are some of my code
Login
if(response){
if(await bcrypt.compare(loginPW, response.password)){
const accessToken = jwt.sign({
email: response.email
},jwtSecret)
res.json({status: 'ok', accessToken: accessToken})
}else{
return res.json({status: 'error', error:'Invalid Credentials'})
}
}
Post request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
just add Authorization header with your token to request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
one possible way is ....on your Post requst result you can store the accessToken in localStorage
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json()).then(({accessToken})=>{
localStorage.setItem('accessToken', accessToken)
});
then retrieve it in all of your requests
const anotherRequst = await fetch('/anything',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('accessToken')}` // get it from localStorage
},
body: ... /// anything
}).then((res) => res.json());
that's the simplest way
... for more advanced techniques, try to use Axios
and you can simply set the default authorization header in all your requsts
axios.defaults.authorization = localStorage.getItem('accessToken')
then any request you make will have the accessToken in its header
Axios.post(....)
Axios.get(...)
....
You can add 'Authorization' headers within your request just like this
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
Or if you're dealing with a big project and you have to send the token with every request then you can use Axios which allows you to add common headers with every request using only one line
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
Docs: https://www.npmjs.com/package/axios

React - GET and POST requests with axios

In my application I need to GET some data (for which I provide the native authtoken).
In the same event, however, I also need to POST a second token to be consumed by a few endpoints, for external backend api calls.
How do I POST this second token using my working code below using axios?
Should I extend Authorization bearer or simply POST Spotify Token as string data?
How so?
My code:
getData(event) {
const {token} = this.props.spotifyToken
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.data)
})
.catch((error) => { console.log(error); });
};
For an async await applied to your code would look something like this.
async getData(event) {
const {token} = this.props.spotifyToken
let getRes = await axios.get(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
let postRes = await axios.post(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
console.log(getRes.data.data);
console.log(postRes.data.data);
};
In this specific case, where a token is needed to fetch data at backend, I found that passing token at url is more suitable, like so:
#endpoint.route('/endpoint/<select>/<user_id>/<token>', methods=['GET'])
def endpoint(name, user_id, token):
# business logic
and:
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint/${select}/${userId}/${this.props.spotifyToken}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
otherwise, backend code would run twice, for POST and GET, which is not desired in my case.

Categories