I'm dealing with Spotify's API but not succeed to automatically get a new access token.
function api() {
$.ajax({
type: 'POST',
url: 'https://accounts.spotify.com/api/token?grant_type=client_credentials',
headers: {
'Authorization': 'Basic myClientIdEncodedToBase64Format:myClientSecretEncodedToBase64Format'
},
success: function(data) {
console.log('Succes ->', data);
},
error: function(error) {
console.log('Error -> ', error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm getting a 400 error. If [i refer the doc][1], '400: Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information'.
What am i doing wrong here ?
Thanks !
Here my code. I add data :
function api() {
$.ajax({
type: 'POST',
url: 'https://accounts.spotify.com/api/token',
data: 'grant_type=client_credentials',
headers: {
'Authorization': 'Basic myClientIdAndMyClientSecretConvertedToBase64'
},
success: function(data) {
console.log('Succes ->', data);
},
error: function(error) {
console.log('Error -> ', error);
}
});
}
Related
I want to use received data from server on client . I use a NodeJS Server with NextJS and React.
I use this function on the server:
function addEmailToMailChimp(email, callback) {
var options = {
method: 'POST',
url: 'https://XXX.api.mailchimp.com/3.0/lists/XXX/members',
headers:
{
'Postman-Token': 'XXX',
'Cache-Control': 'no-cache',
Authorization: 'Basic XXX',
'Content-Type': 'application/json'
},
body: { email_address: email, status: 'subscribed' },
json: true
};
request(options, callback);
}
The function will be run from this point:
server.post('/', (req, res) => {
addEmailToMailChimp(req.body.email, (error, response, body) => {
// This is the callback function which is passed to `addEmailToMailChimp`
try {
var respObj = {}; //Initial response object
if (response.statusCode === 200) {
respObj = { success: `Subscribed using ${req.body.email}!`, message: JSON.parse(response.body) };
} else {
respObj = { error: `Error trying to subscribe ${req.body.email}. Please try again.`, message: JSON.parse(response.body) };
}
res.send(respObj);
} catch (err) {
var respErrorObj = { error: 'There was an error with your request', message: err.message };
res.send(respErrorObj);
}
});
})
The try method is used to verify that an email address could be successfully saved to MailChimp. An appropriate message is sent to the client.
On the Client-Side, i use this function to receive and display the data from the server:
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
}).then(res => {
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
The problem: The email address is saved successfully at MailChimp, but the message is always displayed: 'Error. Please try again later.'from the .catch area. When i log the error from the catch area i get this:
TypeError: Cannot read property 'success' of undefined
Where is my mistake? I have little experience in Node.js environments. I would be very grateful if you could show me concrete solutions. Thank you for your replies.
With fetch theres no data property on the response. You have to call res.json() and return that promise. From there the response body will be read and deserialized.
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => {
console.log(res); //to make sure the expected object is returned
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
Two things you need to change:
Call and wait for res.json() to get the response body as json object.
The result of 1. is your 'data' object that you can use directly
handleSubmit() {
//...
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => res.json())
.then(data => {
if(data.success) {
//...
toaster.success('Subscribed!', data.success);
} else {
toaster.warning('Unable to subscribe!', data.error);
}
}).catch(error => {
//...
});
}
Ext.Ajax.request({
url: 'Employee/Search',
method: 'POST',
headers: { "Content-Type":"application/json","Accept": "application/json","Authorization": "OAuth oauth_token=158ghhBtgf2586525hggfgdf" },
jsonData: {
"FirstName": txtFirstName.getValue()
},
success: function(response) {
},
failure: function(response) {
}
});
This is giving me 401 (Unauthorized Request)
I am using adal.js library by Microsoft, and using the following code:
window.acquireTokenCallback = function (error, token) {
if(error || !token) {
Ext.alert('ADALERROR', error || 'Token empty');
return;
}
// Apply token to all future Ajax requests.
Ext.Ajax.setDefaultHeaders({
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
});
// Load Settings from Server.
me.loadSettings();
};
I use axios version 0.13.1 and if I want to get data with orderBy and limitToFirst parameters, I got 400 Bad request error.
With this http request I get 400 error:
axios({
method: 'get',
url: 'https://tracker-ag.firebaseio.com/groups.json',
params: {
auth: AccessStore.getToken(),
orderBy: "$key",
limitToFirst: 2,
}
}).then(function (response) {
responseHandler(USERS_GET, '', response.data);
})
.catch(function (error) {
console.log("Error during fetching data " + error.message);
});
This http request without orderBy and limitToFirst parameters works:
axios({
method: 'get',
url: 'https://tracker-ag.firebaseio.com/groups.json',
params: {
auth: AccessStore.getToken(),
}
}).then(function (response) {
responseHandler(USERS_GET, '', response.data);
})
.catch(function (error) {
console.log("Error during fetching data " + error.message);
});
I use express-jwt and create my token via jQuery and save it in my localStorage with:
$.ajax({
url: "http://localhost:8080/login",
type: 'POST',
data: formData,
error : function(err) {
console.log('Error!', err)
},
success: function(data) {
console.log('Success!')
localStorage.setItem('token', data.id_token);
}
});
I have a protected route in my backend like:
app.get('/upload',jwt({secret: config.secret}), function(req, res) {
res.sendFile(path.join(__dirname + '/upload.html'));
});
How can I send the token from localStorage with the request header?
You can set the headers in a $.ajax request:
$.ajax({
url: "http://localhost:8080/login",
type: 'GET',
// Fetch the stored token from localStorage and set in the header
headers: {"Authorization": localStorage.getItem('token')}
});
If you are using JWT authentication then this is how you add it to the headers in .ajax() method:
headers: {
Authorization: 'Bearer '+token
}
,
I use the approach below to cover JWT authentication with the result status types
$.ajax({
url: "http://localhost:8080/login",
type: "POST",
headers: { Authorization: $`Bearer ${localStorage.getItem("token")}` },
data: formData,
error: function(err) {
switch (err.status) {
case "400":
// bad request
break;
case "401":
// unauthorized
break;
case "403":
// forbidden
break;
default:
//Something bad happened
break;
}
},
success: function(data) {
console.log("Success!");
}
});
I'm trying to send bitcoin through Coinbase's API, and this is my code:
// create object to send as data
var transaction = {
to : correctusermail, // "my#email.com"
amount_string : amount, // "1.00"
amount_currency_iso : currency // "EUR"
};
// get correct auth key from user
var authq = new Parse.Query(Parse.User);
authq.get(objectid, {
success: function(userObject) {
correctauth = userObject.get("provider_access_token");
console.log(correctauth);
console.log(transaction);
// send post request
// make post request
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
access_token: correctauth,
transaction: transaction
},
success: function(httpResponse) {
response.success(120);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(111);
}
});
},
error: function(userObject, error) {
response.error(150);
}
});
As you can see I'm making sure that my correctauth var is correct by logging it, which works just fine.
All the other variables are correct, I've checked them. So what am I missing? It's probably very small.
From my understanding of the Coinbase API documentation, the access_token should always be part of the URL, e.g.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money?access_token='
+ correctauth,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
transaction: transaction
},
// ... etc ...