I have one request that I want to get token from response and save it in variable because I want to use it in another request as bearer token
/// <reference types="cypress" />
describe("Testing API Endpoints Using Cypress", () => {
it("Login", () => {
cy.request({
method: "POST",
url: "/creditonal",
body: {
"credentials": {
"username": "admin",
"password": "admin"
}
}.then((response) => {
// Get token
})
})
})
})
This is my response
{
"status": "ok",
"statusCode": "0000",
"message": {
"type": "",
"text": ""
},
"errors": [],
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmYTk0YzYzNWRhOWU0NTY0NGYwM2ViMiIsImlzQ2xpZW50IjpmYWxzZSwiaWF0IjoxNjExMjQzNjYyLCJleHBBdCI6MTYxMTI0NzI2MiwiaXNzdWVyIjoiRHJvcHAgVGVjaG5vbG9naWVzIiwicm9sZXMiOlsiRVJ5eGc2Il19.V7cniqE9DrxPRn5GX9wQJtVwPnLrv5Hb3A1SxmBXOO4",
"accessTokenExpiresAt": 3599,
"refreshToken": "983e503a2b194a0190af4cdf0f4d471cf387e4d784044f6ca1fe3f942aad1b5f",
"refreshTokenExpiresAt": 15548399
}
}
You can use token from from request 1 and pass it onto request 2 like this. I have currently used the token as an bearer authorization header.
cy.request({
method: "POST",
url: "/creditonal",
body: {
"credentials": {
"username": "admin",
"password": "admin"
}
}
}).then((response) => {
const token = response.data.accessToken
return token
}).then((token) => {
//Use the value of token anywhere in the second request anywhere
cy.request({
method: 'GET',
url: 'https//example.com',
'auth': {
'bearer': token
}
}).then((response) => {
expect(response.status).to.eq(200)
})
})
I would suggest to go for alias which is easier to use. You just retrieve the response whenever you really need:
it("Login", () => {
cy.request({
method: "POST",
url: "/creditonal",
body: {
"credentials": {
"username": "admin",
"password": "admin"
}
}
}).as('login')
// do more things
cy.get('#login').then(response => {
// whatever you want with response later on
})
})
Related
I want to send a message whenever a button is clicked, but I'm getting 400 Bad Request Errors. It works fine when I do it in Postman.
Here's my jQuery.ajax code:
$.ajax({
method: "POST",
url: 'https://graph.facebook.com/v14.0/me/messages?access_token=<MY_ACCESS_TOKEN>',
data: {
"recipient": {
"id": psid
},
"message": {
"text": "hello, world!"
}
},
contentType: "application/json",
success: function (response) {
console.log(response)
}
})
The Below Code Successfully retrives JSON data but it doesnot work on
localhost and jsFiddle
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.twitter.com/1.1/trends/available.json",
"method": "GET",
"headers": {
"Authorization": "OAuth oauth_consumer_key=\\\"Pd4vyx4AsNv3jdMja0cNCXilN\\\",oauth_signature_method=\\\"HMAC-SHA1\\\",oauth_timestamp=\\\"1537443447\\\",oauth_nonce=\\\"WsA8VV16BfF\\\",oauth_version=\\\"1.0\\\",oauth_signature=\\\"M%2BPZVPbFSnxkxeDxFLxC1eKYHdY%3D\\\""
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
How to change the snippet and status values of an already uploaded video through YouTube API v3 "https://www.googleapis.com/youtube/v3/videos" using AJAX request?
My UPDATED CODE (NOT Working):
$.ajax({
type: "PUT",
dataType: "jsonp",
url: "https://www.googleapis.com/youtube/v3/videos?part=id,snippet,status&key=<API Key>",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + <Access Token>
},
data: $.parseJSON('{"id": "<Video ID>", "snippet": {"title": "New Title", "description": "New Description"}, "status": {"privacyStatus": "unlisted"}}'),
success: function(data, error, completeError) {
alert( JSON.stringify(data));
alert( JSON.stringify(error));
alert( JSON.stringify(completeError));
}
});
Make a PUT request to the videos/update endpoint with the parameter part=id,snippet,status:
HTTP PUT: https://www.googleapis.com/youtube/v3/videos?part=id,snippet,status&key={YOUR_API_KEY}
Body of your request:
{
"id": "VIDEO_ID",
"snippet": { // any snippet fields you want to change
"description": "New Video Description"
},
"status": { // any status fields you want to change
"privacyStatus": "public"
}
}
Here is the code I used when having a play around. It works well though.
It doesn't use JQuery but should point you in the right direction.
function UpdateVideoInfo(video_id){
var resource = {
'snippet':{
'title' : 'test title',
'description' : 'test description',
'categoryId' : 22
},
'status' : {
'privacyStatus' : 'private'
},
'id': video_id
};
post_string = JSON.stringify(resource);
var ajax = new XMLHttpRequest();
ajax.open('PUT', 'https://www.googleapis.com/youtube/v3/videos?part=snippet,status', true);
ajax.setRequestHeader("Authorization", '<?php echo $authorization_header; ?>');
ajax.setRequestHeader("Content-type", "application/json; charset=UTF-8");
ajax.send(post_string);
ajax.onload = function() {
if (ajax.status == 200) {
alert(ajax.responseText);
}
};
}
I have the following piece of JSON:
[
{
"number": "0",
"name": "Russell Westbrook",
"attemptedFG": [
{
"x": "333",
"y": "97",
"made": "true",
"assisted": "false"
},
{
"x": "571",
"y": "389",
"made": "true",
"assisted": "false"
}
],
"attemptedFT": [
{
"made": "true"
},
{
"made": "false"
}
],
"rebounds": "5",
"assists": "8",
"steals": "2",
"blocks": "1",
"turnovers": "3",
"fouls": "4"
}
]
and I'm trying to parse it with this AJAX call using ReactJS:
loadStatsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
All the values in the JSON are still stringified after the AJAX call succeeds. The server sends back a response header with 'Content-Type', 'application/json' so I'm not sure why it's not parsing.
Server-side call:
app.get('/stats.json', function(req, res) {
fs.readFile('stats.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
Thanks a bunch.
When you send a stringified json object from server to client, you need to parse that object to readable javascript object. So, you need to parse json in success event of ajax request:
success: function(data) {
var result = $.parseJSON(data);
}
Now result is a javascript readable object.
So here is my code, i've already made the oauth handshake, and that has given me the authentication token which i'm including in my header. I am simply trying to batch insert some features into an existing table. I keep getting a 400 "parseError" - This API does not support parsing form-encoded input.
Here's some of my code. I have no idea where i'm derping any ideas.
$(document).ready(function(){
$('.pickTrip').bind('click', function(){
var pointData = {
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-87.397980,
44.795067
]
},
"properties": {
"gx_id": "1242342",
"name": "Jimmy Choo",
"phone": "(920)555-4242",
"email": "jchoo#aol.com",
"vehicle": "mazda, b2300, 1994"
}
}
]
};
console.log(pointData);
var url = "https://www.googleapis.com/mapsengine/v1/tables/{table id}/features/batchInsert";
jQuery.ajax({
type: "POST",
url: url,
data: pointData,
dataType: 'application/json',
headers: {
'Authorization': 'Bearer ' + authResult.access_token
},
success: function(response) {
// Log the details of the Map.
console.log(response);
},
error: function(response) {
response = JSON.parse(response.responseText);
console.log("Error: ", response);
}
});
});
});
jQuery takes the object provided in the 'data' parameter and turns the key/value pairs into an encoded query string. You will want to send the raw JS object and make sure it's not marked as form encoded. To do that, change the 'dataType' parameter to 'contentType' and update the data value to take the "stringified" version of the JSON object.
Like this:
data: JSON.stringify(pointData),
contentType: 'application/json',