How to send a token with an AJAX request from jQuery - javascript

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!");
}
});

Related

Getting 400 error status code on client_credentials Spotify API request

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);
}
});
}

Ajax post call throwing an error net::ERR_UNKNOWN_URL_SCHEME

I am trying to make a post call through ajax from my front end to my express server, but I am getting the error net::ERR_UNKNOWN_URL_SCHEME. The code for ajax is below
function sendSteps(encodedLatLangs) {
$.ajax({
url: 'localhost:3000/route',
type: "POST",
dataType: "jsonp",
contentType: "jsonp; charset=utf-8",
crossDomain:true,
data: JSON.stringify({
steps: encodedLatLangs
}),
success: function (response) {
console.log(done);
},
error: function (request,error) {
console.log('Ajax call gave an error');
}
})};
My console is showing this.
This is how I am handling post request to this endpoint on backend
router.post('/route',function (req, res) {
console.log("Hello Received the Data");
res.send("Hello Received the Data");
//Doing something with the received data
});
Can some throw any light on this.
Thanks.
With JSONP you can sending only GET request (JSONP insert script tags into the DOM).
Your data should be a &key=value string and contentType is application/javascript
Try it:
function sendSteps(encodedLatLangs) {
$.ajax({
url: 'localhost:3000/route',
dataType: "jsonp",
contentType: "application/javascript; charset=utf-8",
crossDomain: true,
data: 'steps=' + encodeURIComponent(JSON.stringify(encodedLatLangs)),
success: function (response) {
console.log(done);
},
error: function (request, error) {
console.log('Ajax call gave an error');
}
});
};
Or use JSON (if you are a server owner and can set up CORS).
It can be done by setting "Access-Control-Allow-Origin" in response header.
Something like this. For more details visit https://enable-cors.org/server_expressjs.html
And also we have to remove "data type" and "content type" from the ajax request.
router.route('/route')
.post((req, res, next) => {
controllers
.post(req.body)
.then(data => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.send(message.generateMessage(200, '', data))
})
.catch(err => next(err))
})

Getting an unauthorized error

the overall code is a bit messy as I have been trying different things out and haven't gotten down to organizing them all. I am trying to send a PUT request to the /api/protected with the username and the new email to update the email. This is a protected route which needs the authtoken to access it which I have passed in. I am getting an unauthorized error.
function updateProfile(username, email, authToken, callback) {
const settings = {
url: '/api/protected',
data: {
username: `${username}`,
email: `${email}`,
headers: {
authorization: `Bearer ${authToken}`
},
},
dataType: 'json',
type: 'PUT',
success: callback,
error: error
};
$.ajax(settings);
}
This is the ajax request and now in the server side code:
app.put('/api/protected', jwtAuth, (req, res) => {
const updatedItem = User.update({username: req.body.username}, {$set:{email: req.body.email}})
return res.status(201).json({updatedItem});
});
If we look at the documentation, we see that the headers property should be on the settings sent to $.ajax, not within the data property. To remedy, simply move it out of the data property. For example:
function updateProfile(username, email, authToken, callback) {
const settings = {
url: '/api/protected',
data: {
username: `${username}`,
email: `${email}`,
},
headers: {
authorization: `Bearer ${authToken}`
},
dataType: 'json',
type: 'PUT',
success: callback,
error: error
};
$.ajax(settings);
}
Note that I've also cleaned up the indentation a bit to make it easier to see the correct placement.

How to call Web API from ExtJS with token based authentication

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();
};

Parse webrequest to Coinbase gives 401 not authorized

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 ...

Categories