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.
Related
I have gotten a token using bearer authentication using Ajax. I am unable to pass the token to another Ajax call to connect to another API. I set the alert, and the alert shows the token is passed through the sessionStorage. However, I get the following error. I listed the two Ajax calls below, the first one to get the bearer token, and the second one to use the token in another API call. What am I doing wrong?
POST https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/address/v1/addresses/resolve 401 (Unauthorized)
send # jquery-3.6.0.js:10109
ajax # jquery-3.6.0.js:9690
(anonymous) # Index:1245
dispatch # jquery-3.6.0.js:5430
elemData.handle # jquery-3.6.0.js:5234
Index:1301 {"readyState":4,"responseText":"{\"transactionId\": \"de3465a3-7b79-466b-98be-7a22f1d0a1a0\",\"errors\":[{\"code\":\"NOT.AUTHORIZED.ERROR\",\"message\":\"No access token provided. Please modify your request and try again.\"}]}","responseJSON":{"transactionId":"de3465a3-7b79-466b-98be-7a22f1d0a1a0","errors":[{"code":"NOT.AUTHORIZED.ERROR","message":"No access token provided. Please modify your request and try again."}]},"status":401,"statusText":"Unauthorized"}
$("#btnStartDiscount").click(function () {
$.ajax({
async: true,
crossDomain: true,
url: "https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/oauth/token", //pass your tenant
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
},
data: {
grant_type: "client_credentials",
client_id: "xxxxxxxxxxx", //Provide your app id
client_secret: "xxxxxxxxxxxxx", //Provide your client secret genereated from your app
},
success: function (response) {
console.log(response);
token = response.access_token;
console.log(token);
enterAddressFields();
document.FedExShip.tokenField.value = token;
sessionStorage.setItem("myToken", JSON.stringify(token));
let getToken = sessionStorage.getItem("myToken");
console.log(getToken);
alert("Connected Token " + getToken);
},
error: function (error) {
console.log(JSON.stringify(error));
},
});
});
$("#btnAddrValidate").click(function () {
/*FedEx address validation to validate street lines, city, state, postal code and country code*/
let getToken = sessionStorage.getItem("myToken");
$.ajax({
url: "https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/address/v1/addresses/resolve", //post address
method: "POST",
headers: {
authorization: "'Bearer '+ getToken",
"x-locale": "en_US",
},
data: {
addressesToValidate: [
{
address: {
streetLines: ["7372 PARKRIDGE BLVD", "APT 286"],
city: "IRVING",
stateOrProvinceCode: "TX",
postalCode: "75063-8659",
countryCode: "US",
},
},
],
},
success: function (response) {
console.log(response);
token = response.access_token;
console.log(getToken);
alert("Successfully passed token " + token);
alert("Success");
/* enterAddressFields();*/
},
error: function (error) {
console.log(JSON.stringify(error));
/*alert(this.response);*/
/* alert("Failure");*/
alert("Failed to pass token " + getToken);
},
});
});
I stored the token value as localstorage.token also ,but the result was the same.
I am trying to send the username of a logged-in person from the Client to the Server as a string. I am already sending a file (image) but I also want to send a string as well.
Essentially what I wanna do is in the Server Side File to replace the 'public_id' with username from Client-side.
As you can see below I am already sending the image (file) that I want to the server. I have used console.log(loggedInUser?.username); to show the string that I want to be sent.
Hope this was enough to explain what I am trying to do. Thanks in advance.
Client Side file
console.log(loggedInUser?.username);
const uploadImage = async (base64EncodedImage: string) => {
try {
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({ data: base64EncodedImage }),
headers: { 'Content-type': 'application/json' },
});
} catch (error) {
console.error(error);
}
};
Server side file
app.post("/api/upload", async (req, res) => {
try {
const fileStr = req.body.data;
const uploadedResponse = await cloudinary.uploader.upload(fileStr, {
upload_preset: "geekyimages",
public_id: "public_id",
invalidate: true,
});
console.log(uploadedResponse);
res.json({ msg: "Uploaded" });
} catch (error) {
res.status(500).json({ err: "Something went wrong" });
}
});
Just send both inside a single JSON-Object:
// client side
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({
data: base64EncodedImage,
username: loggedInUser?.username
}),
headers: { 'Content-type': 'application/json' },
});
// server side
const username = req.body.username;
From here
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({ data: base64EncodedImage }),
headers: { 'Content-type': 'application/json' },
});
Just add a username in the body like
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({ data: base64EncodedImage, username: username: loggedInUser?.username || "SOME_DEFAULT_VALUE" }), // The default value is in case you an have a null or undefined username
headers: { 'Content-type': 'application/json' },
You can also prevent this behavior adding this check
if (loggedInUser?.username) ... // The code without default value
else { // A message }
I am using Cypress 4.3.0 version, the baseUrl = "https://tenant-demo.somesitedev.net" has been set in cypress.json file. While I am sending the cy.request() command, it is sending multiple request (please see Fig:1) . Also, when I observed the visit command I could see following Original Url, Resolved Url and Redirects. In this scenario, how do I login to the site using cy.request() command.
before(()=>{
cy.visit('/').then(()=>{
cy.get('input[type="hidden"]').invoke('val').then((val)=>{
const token = val;
cy.login(token);
})
})
})
Cypress.Commands.add('login', (token) => {
const username= 'test1.user';
const password= 'somepassword';
const accessToken = localStorage.getItem('tokens');
const cookieValue = document.cookie.split(';');
const configCat = localStorage.getItem('ConfigCat_');
cy.request({
method: 'GET',
url: '/dashboard',
failOnStatusCode: false,
form: true,
body:{
_token: token,
username,
password
},
headers: {
'accept': 'text/html',
'content-type': 'application/x-www-form-urlencoded',
'authorization': `bearer ${accessToken}`,
'ConfigCat_': `${configCat}`,
'cookie': `${cookieValue}`
}
}).then((res)=>{
visitDashboard();
})
})
const visitDashboard = () => {
cy.visit('dashboard')
}
Fig:1
Fig:2
Somehow I managed to find a way to resolve the problem. Since the baseUrl has got some path extension /auth/login, whenever I trigger a cy.request() it was always redirecting back to login page even though the credentials was correct. Also there were two requests in the console.
So the way I did was to send another cy.request() with GET method with body params immediately after the first POST cy.request() with qs parameters. From the request headers I find out there was a 'token' submitted every time when the user login.
If there is another easy way let me know.
Cypress version : 4.4.0
Inside beforeEach(), grab the 'token' value;
beforeEach(() => {
cy.visit('/');
cy.loadTokens();
cy.get('input[name="_token"]').invoke('val').then((val)=>{
const tokenValue = val;
cy.loginRequest(tokenValue);
})
})
Following is the commands.js file:
Cypress.Commands.add('loginRequest', function (tokenValue) {
return cy.request({
method: 'POST',
url: Cypress.config('baseUrl'),
followRedirect: true,
headers: {
'content-type': 'text/html; charset=UTF-8'
},
qs:{
_token: tokenValue,
username: 'your_username',
password:'your_password'
}
}).then(()=>{
return cy.request({
method: 'GET',
url: 'https://tenant-demo.somesitedev.net/dashboard',
followRedirect: false,
headers: {
'content-type': 'text/html; charset=UTF-8'
},
body:{
_token: tokenValue,
username: 'your_username',
password:'your_password'
}
})
})
});
I've been having a problem all day sending json data via ajax to Express.
My ajax looks like this:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
and my Express Classes routes looks like this:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
I issued a postman post request to the url with this JSON object:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
and Express logged all the details in the console just fine, so it must be a problem with my ajax request as it's giving me an unexpected token u error but I don't know what's causing it. Any ideas?
Try removing the contentType: "application/json",
If you used postman with no headers, most likely this is causing the parser to fail.
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 ...