get data from spotify api using implicit grant flow in vue - api

im new at vuejs and working with api
i wanna connect to spotify api using implicit grant flow
i redirect user to authorize page and get access token, then i set header using axios instance.
this block of code is in main.js
import axios from 'axios'
export const base = axios.create({
baseURL: 'https://api.spotify.com/v1',
header: {
'Authorization' : 'Bearer ' + store.state.accessToken,
}
});
Vue.prototype.$http = base;
and this one is in one of my components that i try to get data from api
mounted() {
this.$http.get('/artists/1vCWHaC5f2uS3yhpwWbIA6')
.then(data => this.albums = data)
.catch(e => this.error = e)
}
but the server responds with 401 error and this message:
Error: Request failed with status code 401
so what do you think?

Related

Vue + axios : has been blocked by CORS policy

I have vue app using axios ,first made axios default values :
import axios from 'axios'
const token ='xxxxxxxxx'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
axios.defaults.baseURL = 'http://xxxxxxxxx/api/v1/'
then in a page I call axios :
<script>
export default {
data : function () {
return {
games : []
}
},
created: async function(){
await this.axios('games/this',{withCredentials: true,}).then((res)=> this.games=res.json)
}
}
</script>
I get this error from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
I tried many solution from posts in this site but don't works
CORS issue should be solved on the backend-side.
If you are using Lumen for backend, please make sure you installed Laravel-Cors
https://github.com/spatie/laravel-cors
Then set allowed_origins to * in the config/cors.php file.
...
'allowed_origins' => ['*'],
...

Vue axios doesnt change header

I am quite new to vue and I am trying to send a request to my api using axios.
I build an interceptor which seems to work (logging is happening)
export default function setup() {
console.log('Http interceptor starting...')
Axios.interceptors.request.use((request) => {
const token = store.getters.token;
if (token) {
request.headers.Authorization = `Bearer ${token}`;
}
console.log(request);
return request
}, (err) => {
return Promise.reject(err);
});
}
If I check the console I can see the request including the token. If I check my network tab in the browser i can see the same request without the token. If I check the console of my api the token is null. Any Ideas?
Edit: If I use postman with the same request and the same token it is working as it shuld

Problem setting API client authorization key in axios

The API is developed using Laravel, I am currently implementing authorization logic using Laravel Passport. the client application is a Vuejs application, Http calls are done using axios.
Passport is perfectly returning a token (i'm using client credentials type of grants). axios offers a way to set default headers by setting axios.defaults.headers.common array. Here is my axios call (implemented in bootstrap.js)
async function a() {
var ret = "";
await axios
.post("/oauth/token", {
"client_id": 7,
"client_secret": "2GmvfxQev7AnUyfq0Srz4jJaMQyWSt1iVZtukRR6",
"grant_type": "client_credentials",
"scope": "*"
})
.then((resp) => {
ret = resp.data.access_token;
})
return ret;
}
a().then((res) => {
console.log(res) //this perfectly loggs the token to the console.
axios.defaults.headers.common["Authorization"] = "Bearer " + res
})
However, all subsequent axios calls are missing the Bearer token header.
You may try to create an axios instance with custom config:
https://github.com/axios/axios#creating-an-instance
Example:
const axios = require('axios').create({
headers: {
'Authorization': 'Bearer: ' + token
}
});
and use it just like you would normally do:
axios.get(url).then(resp => {
//response handler
});
axios.post(url, data).then(resp => {
//response handler
});

vue-resource not passing token in request headers

I'm new to Vuejs 2, currently using vue-resource to retrieve data from the server. However, I would need a token passed in the request header at the same time in order to retrieve the data from the server.
So the problem is, I am unable to retrieve data because the token is not passed into the request header, using vue-resource.
Here is the method that uses the vue-resource's interceptor (to pass in the token) to intercept the GET request:
test () {
this.$http.interceptors.push((request) => {
var accessToken = window.localStorage.getItem('access_token')
request.headers.set('x-access-token', accessToken)
return request
})
this.$http.get(staffUrl)
.then(response => {
console.log(response)
}, (response) => {
console.log(response)
})
}
Documentation for vue-resource, HTTP: https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
When I try to GET the data, i end up with an error 403 (forbidden) and after checking the request headers in the dev tools, I also could not find the token in the request headers.
Please tell me where I went wrong because I'm really new to this so i appreciate any help! Thank you!
Setting interceptors inside the component using $http doesn't work, or at least it doesn't in my testing. If you examine/log this.$http.interceptors right after your push in the test method, you'll note that the interceptor was not added.
If you add the interceptor before you instantiate your Vue, however, the interceptor is added properly and the header will be added to the request.
Vue.http.interceptors.push((request, next) => {
var accessToken = "xyxyxyx"
request.headers.set('x-access-token', accessToken)
next()
})
new Vue({...})
Here is the test code I was using.
Also note, if you are using a version prior to 1.4, you should always call the next method that is passed to the interceptor. This does not appear to be necessary post version 1.4.
please go through this code
import vueResource from "vue-resource";
import { LocalStorage } from 'quasar'
export default ({
app,
router,
Vue
}) => {
Vue.use(vueResource);
const apiHost = "http://192.168.4.205:8091/";
Vue.http.options.root = apiHost;
Vue.http.headers.common["content-type"] = "application/json";
Vue.http.headers.common["Authorization"] = "Bearer " + LocalStorage.get.item("a_t");
Vue.http.interceptors.push(function(request, next) {
console.log("interceptors", request);
next(function(response) {
});
});
}

vue-resource interceptor for auth headers

I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.
I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:
methods: {
getUser () {
this.$http.get('http://localhost:8000/api/user',
{
headers: {
'Authorization': 'Bearer eyJ0e.....etc',
'Accept': 'application/json'
}
}).then((response) => {
this.name = response.data.name
});
},
However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.
Based on the vue-resource readme I am trying this in my main.js:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
And then back in my component I now just have:
this.$http.get('http://localhost:8000/api/user').then((response) => {
this.name = response.data.name
});
Problem:
When I specify the headers in the get itself, I get a successful response, but when I pass them through the interceptor I get back a 401 Unauthorized from the server. How can I fix this to respond successfully while using the interceptor?
Edit:
When I use dev-tools to view the outgoing requests I see the following behavior:
When making the request by supplying the headers to $http.get, I make a successful OPTIONS request and then a successful GET request with the Authentication header being supplied to the GET request.
However, when I remove the headers from the $http.get directly and move them to the interceptor, I only make a GET request and the GET does not contain the Authentication header, thus it comes back as a 401 Unauthorized.
It turns out my problem was the syntax for which I was setting the headers in the interceptor.
It should be like this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer eyJ0e.....etc')
request.headers.set('Accept', 'application/json')
next()
})
While I was doing this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
Add this option:
Vue.http.options.credentials = true;
And use the interceptors for global way:
Vue.http.interceptors.push(function(request, next) {
request.headers['Authorization'] = 'Basic abc' //Base64
request.headers['Accept'] = 'application/json'
next()
});