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

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}.

Related

React native API request with fetch() to getmati API respond well in postman, but not working in App and got 400 error

I am trying to integrate mati api for KYC flow into my React native app.
In order to get auth token, I referenced the documentation below.
https://docs.getmati.com/reference/authentication
Testing in postman works fine and got the response of auth_token.
However, in the React native code, it got 400 error.
Please help me figure this out.
The code snippet:
const myoptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
body: new URLSearchParams({grant_type: 'client_credentials'}),
};
fetch('https://api.getmati.com/oauth', myoptions)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
The error is:
LOG {"code": 400, "message": "Missing parameter: `grant_type`", "name": "invalid_request", "status": 400, "statusCode": 400}
From the documentation you mentioned it seems like its accepting form data and you are sending search params. Try this
const formData = new FormData();
formData.append("grant_type","client_credentials");
const myoptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
body: formData,
};
fetch('https://api.getmati.com/oauth', myoptions)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
I found the error and figured out as below.
const body = new URLSearchParams({grant_type: 'client_credentials'});
const myoptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
body: body.toString(),
};
fetch('https://api.getmati.com/oauth', myoptions)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
In react native, we must send the body as string, it works well and get the right response.
Thank you.

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

how to fetch data from this api using 'POST' method in javascript

url---http://eign-backend.herokuapp.com/property/get-property/17/
Do i have to write complete url like till "/17/" or what!
const response=await fetch('url',{
method:'POST',
body: JSON.stringify(
{
//what should I write here
}
),
headers:{
headers: {'Content-Type':'application/json'},
}
})
const data=await response.json();
console.log(data);
}
First argument in fetch is the actual url
const response=await fetch('http://eign-backend.herokuapp.com/property/get-property/17/',{
method:'POST',
body: JSON.stringify(
{
//what should I write here => write whatever you want to send in this post request's body
}
),
headers:{
headers: {'Content-Type':'application/json'},
}
})
const data=await response.json();
console.log(data);
Consider reading some documentation first
You can directly make a POST request on that URL. It's OK to send a POST request without a body and instead use query string parameters but then it should have been a get request instead of POST if there is no need for the body. But be careful if your parameters contain characters that are not HTTP valid you will have to encode them.
var requestOptions = {
method: 'POST',
redirect: 'follow'
};
fetch("http://eign-backend.herokuapp.com/property/get-property/17/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
This is the fetch call that I have used.
try this
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});

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.

How to use Authorization Header in React Native fetch to make a get request using Yelp API

I am trying to make a post request using FETCH in react-native. I am getting a validation error. What am I missing here?
_fetchYelp(){
let data = {
method: 'POST',
body: JSON.stringify({
'client_id': 'id',
'client_secret': 'secret',
'grant_type': 'client_credentials'
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
}
return fetch('https://api.yelp.com/oauth2/token', data)
.then(response => response.json());
}
Error
status 400
timeout 0
response {"error":{"code":"VALIDATION_ERROR",
"description":"client_id or client_secret parameters not found. Make sure to provide client_id and client_secret in the body with the application/x-www-form-urlencoded content-type"}}
response_url https://api.yelp.com/oauth2/token
Thank you.
getAccessToken() {
let formData = new FormData();
formData.append('grant_type', 'client_credentials')
formData.append('client_id', 'yourID')
formData.append('client_secret', 'yourSecret')
let headers = new Headers();
return fetch('https://yourBaseUrl/oauth2/token/', {
method: 'POST',
headers: headers,
body: formData,
})
.then((response) => response.json())
}

Categories