This question already has answers here:
How to send authorization header with axios
(12 answers)
Closed 4 years ago.
I'm new to Vue.js and want to make a request in a component to a restricted api:
computed: {
token () {
return this.$store.getters.getToken;
},
...
created () {
axios
.get( this.BASE_URL + '/profile/me')
.then( res => {
this.profile = res.data;
console.log('profile is:', res.data);
})
.catch(error => console.log(error))
},
The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401 error in response.
And when I try
axios.defaults.headers.common['Authorization'] = this.token;
before the get request I receive OPTIONS /profile/me instead of GET /profile/me in the server logs.
How can I fix it?
Axios get() request accept two parameter. So, beside the url, you can also put JWT in it.
axios.get(yourURL, yourConfig)
.then(...)
In your case yourConfig might be something like this
yourConfig = {
headers: {
Authorization: "Bearer " + yourJWTToken
}
}
Also you can read about what you can put in your config here https://github.com/axios/axios.
Just search for "Request Config"
This works for me, try like -
let JWTToken = 'xxyyzz';
axios
.get(this.BASE_URL + '/profile/me', { headers: {"Authorization" : `Bearer ${JWTToken}`} })
.then(res => {
this.profile = res.data;
console.log('profile is:', res.data);
})
.catch(error => console.log(error))
Related
so basically under guidance of the Spotify WebAPI doc I am trying to request an access token via Client Credentials method. Spotify API Doc. I want to use a regular HTTP fetch request, I can not use any 3rd party libraries. I am getting a 400 return status error response: {error: "unsupported_grant_type", error_description: "grant_type parameter is missing"}. However I believe my request should be formated correctly for its grant type. I have looked at tons of articles, MDN doc, and the Spotify doc and I can not figure out why this is not working. I will include the code which I have obviously taken the api keys out of but they are correct. Link to code.
import React, { Component, useState , useEffect } from 'react';
//Custom IMPORTS:
import '../PageCss/HeaderSection.css'
const Spotify = () => {
const [baseUrl, setBaseUrl] = useState("https://accounts.spotify.com/api/token");
const [token, setToken] = useState([]);
const [currentStatus, setStatus] = useState(false);
const client_id = '';
const client_secret = '';
const data = { grant_type: 'client_credentials' };
useEffect(() => {
fetch(baseUrl,
{
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Basic ' + (client_id + ':' + client_secret).toString('base64')
},
redirect: 'follow',
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
return Promise.reject(new Error("Response Error!"));
}
else {
return response.json();
}
})
.catch((err) => {
console.log(err);
})
.then((json) => {
try {
setToken(json.results);
setStatus(true);
console.log("TOKEN:" + token)
}
catch
{
return Promise.reject(new Error(`State Error!: Data: ${token} , Connection:${currentStatus}`));
}
})
.catch((err) => {
console.log(err);
})
}, [baseUrl]);
return (
<div >
</div>
)
};
export default Spotify;
My application is a react app, hosted on GitHub. It's a fully functioning site and everything else is working fine. My other API fetch calls are working fine so I know this one must have an issue in it. The only line of code giving me an error is this 400 status from the fetch request.
Hey so I actually got the inital token request to work with this code:
fetch(baseUrl,
{
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
Inspired by the OAuth doc and some more researching. It works now and I have a token from Spotify.
I am using React + Redux on the front end and Spring for the backend. The reponse header contains Authorization header when viewed on browser and in postman but not when trying to access in javascript. I have added the photos showing response headers in network tab and on console tab. And also i am using axios for the request.
auth.js
...
export const authInit = (data) => {
return dispatch => {
dispatch(authInitStart());
axios.post('/login', data)
.then(response => {
if(response.status === 200){
const param = {
'Authorization': response.headers.Authorization
};
console.log("Authorization----" + JSON.stringify(response));
console.log("Param----" + JSON.stringify(param));
localStorage.setItem('Authorization', param['Authorization']);
dispatch(authInitSuccess(param['Authorization']));
}else{
dispatch(authInitFail('Request failed'));
}
}).catch(err => {
dispatch(authInitFail('Network error'));
});
};
};
...
param object is empty here
What can be the issue?
Access-Control-Expose-Headers: Authorization
response.headers.get('Authorization')
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
I'm trying to make a POST request using axios to my firebase cloud-function on form submit in react app. But I get '500' error everytime I make a request with an html-page response This app works best with javascriot enabled.
Latest Update:
It looks like there is no issue with cloud function
code. Rather more of a react-component issue. I used Postman to send
the POST request with header prop Content-Type set to application/json
and sending body in raw format {"email": "example_email"} and got
expected response from the cloud function. But when sent the request from
react component above, I get an html file response saying the app
works best with javascript enabled
I've tried setting Content-Type to both Application/json and multipart/form-data as I suspected it to be an issue but still got no luck.
Following is my code for cloud function and react submit form:
Cloud Function
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true })
const runThisFunc1 = require(./libs/runThisFunc1);
const runThisFunc2 = require(./libs/runThisFunc2);
exports.wizardFunc = functions.https.onRequest((request, response) => {
cors(request, response, () => {
let email = request.body.email;
try {
return runThisFunc1(email)
.then(data => {
console.log("Word Done by 1!");
return runThisFunc2(data);
})
.then(res => {
console.log("Word Done by 2!");
return response.status(200).send("Success");
})
.catch(err => {
console.error("Error: ", err.code);
return response.status(500).end();
});
}catch(err) {
return response.status(400).end();
}
});
});
React-Form-Component Snippet
import axios from 'axios'
...
handleSubmit = e => {
e.preventDefault()
const { email } = this.state
axios({
method: 'post',
url: `${process.env.REACT_APP_CLOUD_FUNCTION_ENDPOINT}`,
data: { email: email },
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
})
.then(res => {
//do something with reponse here
})
.catch(error => {
console.error(error)
})
}
...
Is there something wrong I am doing in the code or the request config is wrong?
This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 3 years ago.
I'm trying to create a login form. when I'm testing the service with Postman, I will get a body object with status code and etc.
But, with JavaScript fetch, I can't get body object and I just received an error:
export const login = (username,password) => {
return dispatch=>{
const basicAuth = 'Basic ' + btoa(username + ':' + password);
let myHeaders = new Headers();
myHeaders.append('Authorization', basicAuth);
myHeaders.append('Content-Type', 'application/json');
fetch(`${baseUrl}api/user/login`, {
withCredentials: true,
headers: myHeaders
})
.then(function (response) {
return response.json();
})
.then(function (json) {
dispatch(setLoginInfo(json))
})
.catch(err =>{
console.log(err)
dispatch(loginFailed())
});
}
}
I need to get status code in fetch.
The status code is the status property on the response object. Also, unless you're using JSON with your error responses (which some people do, of course), you need to check the status code (or the ok flag) before calling json:
fetch(`${baseUrl}api/user/login`, {
credentials: "include", // ¹ See note below
headers: myHeaders
})
.then(function(response) {
console.log(response.status); // Will show you the status
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
return response.json();
})
.then(// ...
Not checking that the request succeeded is such a common mistake I wrote it up on my anemic old blog.
¹ You had withCredentials: true, but the documentation says it's credentials: "include". (Thank you aderchox for pointing that out.)
The status is present in the response object. You can get it inside your first then block
.then(function (response) {
console.log(response.status);
return response.json();
})
Since you are returning response.json(), the subsequent then and catch only gets the result of response.json() which is the body of the response.
Able to get the response in postman. But unable to get in axios. Getting html as response. What would be the problem?
import axios from 'react-native-axios';
var config = {
headers: {
'Content-Type': 'Application/Json',
'JsonStub-User-Key': '__USER__KEY',
'JsonStub-Project-Key': '__PROJECT__KEY'
}
};
export async function menuListByCategories() {
// simulate an asynchronous operation
const url = "http://jsonstub.com/burgers";
axios.get(url, {config})
.then((response) = > {
console.log(response.data);
})
.
catch ((error) = > {
console.log("axios error:", error);
});
}
Update: check the response of this code
You can add data: {} in config in order not to have Content-Type removed by axios. Check the answer of the question below.
Jsonstub response not showing