I was wondering how to write this python request in javascript:
url = "something.something"
data = {"name":"description"}
auth = ("user","11111")
x = requests.post(url, json=data, auth=auth)
I have this so far:
fetch(`something.something`, {
method: 'POST',
header: {
'Content-Type': 'application/json',
'Authorization': 'user:11111',
},
body: {
"name": "description"
}
})
But I have an 403. My guess is that the authorization is formatted incorrectly.
auth = ("user","11111")
x = requests.post(url, json=data, auth=auth)
This uses HTTPBasicAuth for authorization.
Basic HTTP Auth requires the credentials to be passed in the Authorization header like this:
Authorization: Basic <base64(user:password)>
So the javascript example should look something like:
fetch(`something.something`, {
method: 'POST',
header: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('user:11111'),
},
body: {
"name": "description"
}
})
Related
Using Spotify Documentation for Client Credential Flow
(https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/)
I was able to create an API request in javascript:
function getoAuth () {
const client_id = id;
const client_secret = secret;
fetch("https://accounts.spotify.com/api/token", {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic' + (client_id + ":" + client_secret).toString('base64')
},
form: {
grant_type: 'client_credentials',
},
json: true
})
}
But I'm receiving the following error: {"error":"unsupported_grant_type","error_description":"grant_type parameter is missing"}
Why is this failing?
Check the fetch library docs, you have to pass the formdata through body field.
https://developer.mozilla.org/en-US/docs/web/api/fetch
fetch("https://accounts.spotify.com/api/token", {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic<>'
},
body: new URLSearchParams({
'grant_type': 'client_credentials'
}),
json: true
})
I want to send a post with fetching. But I get 401 error: www-authenticate: Bearer error="invalid_token".
I am using Userfront.accessToken() but It did not work.
How can I get accestoken for bearer authentication?
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${Userfront.accessToken()}`,
},
}).then((res) => res.json());
};
Note:
console.log(`Bearer ${Userfront.accessToken()}`);
Bearer [object Object]
Can you try this? I see this from https://userfront.com/guide/auth/
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
JSON.stringify(Userfront.accessToken()) please stringify that object to understand what is going on there then if there is accessToken returning from that function put that string.
I just realized in the doc;
To handle a request like this -Userfront.accessToken()-, your backend should read the JWT from
the Authorization header and verify that it is valid using the public
key found in your Userfront dashboard.
https://userfront.com/guide/auth/
fetch('https://api.example.com', {
method: 'GET'
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
});
Thank you all for your answers.
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
In this application, token gets a different name.
When I look from inspects, I use it and it works!
I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.
I am trying to create a POST request in my reactjs app based on the following API request example:
Example API request
curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I'm supposed to be base64 encoding the text following "Basic" within the header.
How do I create this request in javascript using axios? This is what I have so far:
async componentDidMount() {
const encodedString = new Buffer('1ff56abe7792f426ea41a771d707d6690:1b2cca2dedd3949b0a6c5e1582446c9c5').toString('base64');
const [initSpotResponse] = await Promise.all([
axios.post('https://accounts.spotify.com/api/token', { headers: { 'Authorization': `Basic ${encodedString}` } })
]);
}
How do I include the "grant_type=client_credentials" part?
According to axios’ README, this is the Request method aliases for POST requests
axios.post(url[, data[, config]])
axios.post('https://accounts.spotify.com/api/token',
{ data: { grant_type: ‘client_credentials’} },
{ headers: { 'Authorization': `Basic ${encodedString}` } }
)
You could also do
const options = {
url: ‘https://accounts.spotify.com/api/token',
method: 'POST',
headers: { 'Authorization': `Basic ${encodedString}` },
data: { grant_type: ‘client_credentials’}
};
axios(options);
I am trying below javascript code to subscribe on mailchimp. flow wise working good but i am getting error like not authorize because may be i am not passing api key correctly. please help to solve my issue
var request = new Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
})
});
// Now use it!
fetch(request).then(function (data) {
console.log(data);
});
You need to add your authentification details with your username and api key. You can do it with the auth parameter:
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
Just add that to your request object:
Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
}),
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
});
I looked at the documentation in the getting started section of the developer mailchimp api: here and I converted the curl examples to javascript code using this page. Let me know if it worked.