async create() {
const data = {
name: this.name
};
const headers = {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.token}`
};
axios
.post("URL", data, headers)
.then(res => {
console.log('SUCCESS');
})
.catch(err => console.log(err.response));
}
The token from the login component. The token is loaded correctly as the POST request returns success when tried in Postman but the axios call returns
{ message: 'Unauthenticated.' },
status: 401,
statusText: 'Unauthorized'
Any pointers would be appreciated to identify the direction or root of this error.
You're passing the headers to the axios incorrectly. Try this:
const headers = {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.token}`
};
axios.post(URL, data, { headers })
That's why your Authorization header is not included in your request and the server returns 401.
Related
I'm working through this tutorial on creating an app that uses the Spotify API. Everything was going great until I got to the callback portion of authenticating using the authentication code flow.
(I do have my callback URL registered in my Spotify app.)
As far as I can tell, my code matches the callback route that this tutorial and others use. Significantly, the http library is axios. Here's the callback method:
app.get("/callback", (req, res) => {
const code = req.query.code || null;
const usp = new URLSearchParams({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: "authorization_code",
});
axios({
method: "post",
url: "https://accounts.spotify.com/api/token",
data: usp,
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
},
})
.then(response => {
console.log(response.status); // logs 200
console.log(response.data); // logs encoded strings
if (response.status === 200) {
res.send(JSON.stringify(response.data))
} else {
res.send(response);
}
})
.catch((error) => {
res.send(error);
});
Though the response code is 200, here's a sample of what is getting returned in response.data: "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0003E�˒�0\u0000Ee�uS\u0015��\u000e�(\b\u0012h\u0005tC%\u0010\u0014T\u001e�����0��^:���p\u0014Ѻ\u000e��Is�7�:��\u0015l��ᑰ�g�����\u0"
It looks like it's encoded, but I don't know how (I tried base-64 unencoding) or why it isn't just coming back as regular JSON. This isn't just preventing me logging it to the console - I also can't access the fields I expect there to be in the response body, like access_token. Is there some argument I can pass to axios to say 'this should be json?'
Interestingly, if I use the npm 'request' package instead of axios, and pass the 'json: true' argument to it, I'm getting a valid token that I can print out and view as a regular old string. Below is code that works. But I'd really like to understand why my axios method doesn't.
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[stateKey] : null;
res.clearCookie(stateKey);
const authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
},
headers: {
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`,
},
json: true,
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
const access_token = body.access_token;
const refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { Authorization: 'Bearer ' + access_token },
json: true,
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect('/#' + querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
}));
} else {
res.redirect(`/#${querystring.stringify({ error: 'invalid_token' })}`);
}
});
});
You need to add Accept-Encoding with application/json in axios.post header.
The default of it is gzip
headers: {
"content-type": "application/x-www-form-urlencoded",
'Accept-Encoding': 'application/json'
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
}
i'm studying with React Native,
but i can't get response properly
my fetch code is :
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response);
the response is :
the api response which i get from api when i try postman:
my php api is :
but my debugger console response is
fetch() function return a promise, so you should resolve this promise using one of this 2 methods:
1/ Using .then()
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
).then(response => {
console.log(response); //<- your response here
}).catch(error => {
console.log(error); //<-catch error
});
2/ Using async/await syntax: you should add async keyword on the function where you call fetch
async getResponse(){
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response); //<- your response here
} catch(e){
console.log(e);<-catch error
}
}
You can send it using formdata:
let formData = new FormData();
formData.append('firstname', 'test');
If you do this, you don't have to use JSON.stringify:
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: data
}
...
fetch is an asynchronous method, meaning it needs a .then callback. The data that immediatley comes from this then has a json() method attached to it to retrieve the actual data in a readable format.
fetch("http://192.168.1.106/little_api/index.php", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => response.json())
.then(data => {
console.log(data) // this should return your data
})
.catch(err => console.log(err))
As Mahdi N said in his response, you can use the async/await syntax to retrieve the data without needing the nested callbacks.
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);
});
Burned two hours of my life on this and wondering if fresh eyes can help.
I am attempting to contact auth0 to get access token for the management API.
The provide sample code, using request module, which works perfectly (I have replaced the key/secret values):
var request = require("request");
var options = { method: 'POST',
url: 'https://dev-wedegpdh.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"myID","client_secret":"mySecret","audience":"https://dev-wedegpdh.auth0.com/api/v2/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
res.json(JSON.parse(response.body).access_token)
});
I have my ID and Secret stored in .env file, so was able to adjust to this, which also works fine:
var options = { method: 'POST',
url: 'https://dev-wedegpdh.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body:
JSON.stringify({
grant_type: 'client_credentials',
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: 'https://dev-wedegpdh.auth0.com/api/v2/'})
}
request(options, function (error, response, body) {
if (error) throw new Error(error)
res.json(JSON.parse(response.body).access_token)
})
I try to make the exact same request using axios and I receive 404 error:
let response = await axios.post(
'https://dev-wedegpdh.auth0.com/api/v2/oauth/token',
JSON.stringify({
grant_type: 'client_credentials',
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: 'https://dev-wedegpdh.auth0.com/api/v2/'
}),
{
headers: {'content-type': 'application/json'},
}
)
I have tried several different formats or configurations for the post function including those found
here and here etc.
Anyone see what I am doing wrong???
In axios post body, you need to send data as JSON, no need to use JSON.stringify.
let response = await axios.post(
"https://dev-wedegpdh.auth0.com/api/v2/oauth/token",
{
grant_type: "client_credentials",
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: "https://dev-wedegpdh.auth0.com/api/v2/"
},
{
headers: { "content-type": "application/json" }
}
);
I don't know what I did wrong and need help.
function loadDoy() {
axios({
method: 'post',
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json',
},
url: apiPostUrl,
data: {
user: "webuser",
password: "m0nk3yb#rz",
layout: "Main Menu"
},
})
.then(function(response) {
this.token = response.data.token;
//if login token works then get records
getRecords();
})
.catch(function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
});
}
You can use 'crossDomain': true at your header of axios post, this is due to cors error. Your browser is making a Preflight Request, which uses the OPTIONS HTTP method. This is to check whether the server will allow the POST request – the 405 status code is sent in the response to the OPTIONS request, not your POST request
In this case, the following is causing the request to be preflighted:
if the Content-Type header has a value other than the following:
application/x-www-form-urlencoded
multipart/form-data
text/plain
The value for the Content-Type header is set to application/json;charset=utf-8 by axios. Using text/plain;charset=utf-8 or text/plain fixes the problem: You may try using like below.
source: App Script sends 405 response when trying to send a POST request
axios({
method: 'post',
headers: {
'crossDomain': true,
//'Content-Type': 'application/json',
'Content-Type': 'text/plain;charset=utf-8',
},
url: apiPostUrl,
data: {
user: "webuser",
password: "m0nk3yb#rz",
layout: "Main Menu"
},
})
.then(function(response) {
this.token = response.data.token;
//if login token works then get records
getRecords();
})
.catch(function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
});