VueJS GET request with Bearer token - vue.js

I am experimenting with Kentico Delivery Preview API using VueJS, which allows you to get unpublished content by submitting a bearer token for authorisation (https://developer.kenticocloud.com/reference#authentication). However, no matter what I do I get a 401 in response. PROJECT_ID, ITEM_NAME and TOKEN are all correct, taken from the project, so it's not a typo issue. I admit I don't have much experience with auth, but any help would be appreciated:
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
mounted () {
axios
.request({
url: '/items/ITEM_NAME',
method: 'get',
baseURL: 'https://preview-deliver.kenticocloud.com/PROJECT_ID',
headers: {
'Authorisation': 'Bearer TOKEN'
}
})
.then(response => {
console.log(response.data)
})
}
})

As pointed out by Walter in the comments, I spelt Authorization with an S rather than a Z.. because I'm English. Whoops.

Use create to config axios headers before your request
const TOKEN = 'Token';
const BASEURL = 'https://preview-deliver.kenticocloud.com/PROJECT_ID';
const ENDPOINT = '/items/ITEM_NAME';
axios.create({
baseURL: BASEURL,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+TOKEN
}
})
.get(ENDPOINT)
.then(res => {
console.log(res);
});

Related

req.body is unidentified in express api

I am implementing stripe payment in my react native app and created express api to get clientSecret Intent. So I want to make payment of the amount which I send from my api to api. But in api, I am getting nothing in the request body.
This is how I am calling my Apis
let data={totalAmount:amount, name:'XYZ_Name'}
fetch('http://10.0.2.2:3500/create-payment-intent', {
method: 'POST',
headers: { "Content-Type": "application/json" },
// "Content-Type" : "application/json",
body:data,
})
And this is my express api;
const app = express();
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.post('/create-payment-intent', async (req,res)=>{
console.log('api Data',req.body.amount);
const paymentIntent = await stripe.paymentIntents.create({
amount:5000, //$50
currency:'gbp',
});
res.send({
clientSecret: paymentIntent.client_secret,
paymentIntent,
})
})
app.listen(3500,()=>{console.log('API Running!')});
I see two issues with the frontend code you shared.
First, you should replace totalAmount: amount by amount: amount, since the backend code is using req.body.amount.
Second, you can't directly send a JavaScript object using fetch, you need to convert it into a string with JSON.stringify(data).
With these two fixes, your frontend code should look like this:
let data= { amount: amount, name: 'XYZ_Name' };
fetch('http://10.0.2.2:3500/create-payment-intent', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
})
Note that I wouldn't recommend to pass the amount from the frontend to the backend, since a malicious user could directly change the amount in their browser.
Your data must be stringified
let data = { totalAmount:amount, name:'XYZ_Name' }
fetch('http://10.0.2.2:3500/create-payment-intent', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
})

Axios Get Authorization Not Working In Vue But Worked on POSTMAN (Post method on vue worked)

I'm Using vue for the clientside. And somehow the Authorization is not working with Get method in axios. I tried using POSTMAN and it's working like it should be. Is there any chance that I missed something?
getCurrentPeriode() {
return new Promise((resolve, reject) => {
axios.get(TABLE_NAME,{params: {"X-API-KEY": API_KEY, command:"getCurrent"}}, {
headers:{
'Authorization': `Basic ${token}`
}
})
.then((response) => {
resolve(response.data[0])
}) .catch(err => {
reject(err.response.data)
})
})
}
The token:
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
I get this error: Uncaught (in promise) {status: false, error: "Unauthorized"}
In postman (it's worked):
I've tried with post method in axios and it's working. Yes I've set up CORS. Yes I've allowed Get method in my server side (coz it's working in postman)
Post method is working like normal, here's the code:
postNewPeriode(date) {
return new Promise((resolve, reject) => {
const data = new FormData()
data.append("dateStart", date.dateStart)
data.append("dateEnd", date.dateEnd)
data.append("X-API-KEY",API_KEY)
axios.post(TABLE_NAME,data, {
headers:{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${token}`
}
})
.then((response) => {
resolve(response)
}) .catch(err => {
reject(err.response.data)
})
})
},
Am I missing something in my axios get or I should use different approach? Thanks for the answer
For Axios GET, the headers should be the second argument, while for PUT and POST the body is the second and the headers the third, as you did.
Try using the headers as the second argument on GET.
This should work:
axios.get( TABLE_NAME,
{
headers:{'Authorization': `Basic ${token}`},
params: {"X-API-KEY": API_KEY, command:"getCurrent"}
}
)

Problem put axios update user Strapi and NuxtJS

I have a problem with the right in strapi.
I create user with the role Authenticated and try modified the data with axios.
But it is impossible has modified because return forbidden. I look if the user has right, Update is check in role authenticated.
If i check update in role public, my modification with axios is ok. Why ? I don't undestand the problem.
My code for send
.put(
`https://localhost:4000/users/${this.data.id}`,
{
headers: {
Authorization: `Bearer ${token}`
},
Nom: 'JEAN'
}
)
.then((res) => {
// Handle success.
console.log(res)
})
.catch((error) => {
// Handle error.
console.error('An error occurred:', error)
})```
Thank you
I'm not sure the axios request has the right format.
According to this documentation - https://github.com/axios/axios#axiosconfig
This probably should look like this:
axios({
method: 'put',
url: `https://localhost:4000/users/${this.data.id}`,
data: {
username: 'JEAN'
},
headers: {
Authorization: `Bearer ${token}`
}
});

Accessing bearer token from axios

What code can I use to access a bearer token that's been stored in localStorage?
const apiClient = axios.create({
baseURL: 'http://localhost:5000/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'.
Authorization: ???
}
});
I'm having trouble sending auth headers using a axios Service. When I hardcode the existing bearer token it works, but how can I dynamically access that for each user as it changes?
This is what worked! Thanks to DigitalDrifter for showing me the getItem function in localStorage.
I've been storing the bearer token in 'user' state, so I retrieved the object, parsed it, then inserted it into the Authorization header.
const user = JSON.parse(localStorage.getItem('user'));
const token = user.token;
const apiClient = axios.create({
baseURL: 'http://localhost:5000/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
});
A request interceptor can be used to set the Authorization header prior to each outgoing request.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
let token = localStorage.getItem('bearer_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

How can I make a basic authorization with angular HttpClient and connect with an api Request?

well i have a problem i tried to connect an api with basic authorization but the server donĀ“t give me access it return a 401(unautorized) my code is:
getApi() {
console.log('here i am in the method for get extensions');
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ***********************'
});
const options = {
headers,
withCredentials: true
};
// tslint:disable-next-line:max-line-length
return this.http.post('https://10.100.43.241/json', this.jsonBody, options).map((response: Response) => {
const resToJSON = JSON.stringify(response);
console.log('i am going to return jsonfrom method');
return resToJSON;
});
}
i tried too with postman an it is working as well. i really need to know how can i solved this problem of connection or authorization
note: i am not the administrator about the server
Try this architecture.
Component:
this._appApiService.getApi(this.jsonBody).subscribe(result => {
this.resToJSON = result;
});
Service:
getApi(jsonBody: any) {
// add authorization header with jwt token
let headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.token });
let options = { headers: headers };
return this.http.post(this.baseUrl + 'https://10.100.43.241/json', this.jsonBody , options);
}