I can't access response body Cypress Api Testing - api

I want to automate the api using Cypress, but I can't access the response body.
Use this path cy.log(JSON.stringify(response.body.payload[0]
Api Response
Code
context('GET /Auth', () => {
it('should return a list with all products', () => {
cy.request({
method: 'GET',
url: 'https://auth.plus.a101.com.tr/api/homepage/punch-cards/20149126',
headers: {
'Authorization' : 'Bearer ' + access_token
}
})
.then((response) => {
expect(response.status).to.eq(200)
cy.log(JSON.stringify(response.body.payload[0]))
});
});
});
I get error

You have to convert your response object a json string and then parse it. Instead you can try the following:
cy.request({
method: 'GET',
url: 'https://auth.plus.a101.com.tr/api/homepage/punch-cards/20149126',
headers: {
'Authorization' : 'Bearer ' + access_token
}
}).then((response) => {
response = JSON.stringify(response)
var jsonData = JSON.parse(response)
cy.log(response.body.payload[0])
});

Related

my react-native app fail to send body in POST request to backend url

As i am trying to send my data in form of body in backed url as in backed i have made something if it dont receive body it will send sucess: false, msg: haven't received body else sucess: true, msg: jwt token as if i make request from post man with same data it's working but sending via. native app it fails to send.. any help will be helpfull
As 1st request is from postman and 2nd from my app
const handleLogin = (Enrno, Pass) => {
setError(null);
setIsLoaded(false);
setItems([]);
fetch(config.url + "/login", {
method: "POST",
header : {
Accept : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
"enrno": Enrno,
"password" : Pass
})
})
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
alert(items[0].msg);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
};
I think you need to put these to headers, not header.
Accept : 'application/json',
'Content-Type' : 'application/json'
So, it should look like this.
fetch(config.url + "/login", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
enrno: Enrno,
password : Pass
})
})

How to fetch Webservice which takes string parameter?

I try to fetch webservice method. However, it takes string. How can I send string parameter to webservice ?
I tried like this :
fetch('url/MethodName', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json',
}),
})
where should I put string parameter ?
by mozilla
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
send Json data as parameter
You can do that with fetch, but try to use Axios for making http requests
https://kapeli.com/cheat_sheets/Axios.docset/Contents/Resources/Documents/index

Fetch is not working

I am waiting for successful JSON from server:
{"...."}
Actual Behavior
I get
SyntaxError: Unexpected token b in JSON at position 0
b is the first letter of word "badlogin". It responds server when sent wrong combination of userName and password. But when I use Postman with the same key values combination on the same address I get correct rosponse from the server.
Steps to Reproduce
fetch('http://....', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userName: "react",
password: "123",
})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.message);
if(responseJson.success === true) {
alert('successufuly loged');
}
else{
console.log(responseJson.message);
alert(responseJson.message);
}
})
}
}
You are trying to parse a string. This is the error. Instead of always parse the json, just add a clausule to check if the request was made with success
}).then((response) => {
if(!response.ok) {
// handle your error here and return to avoid to parse the string
return
}
return response.json()
})
.then()
Look like the response you got is not json
Try to check what is the response you are getting first:
.then((response) => response.text())
.then((responseJson) => {
console.log(responseJson);
}
I solved this issue by using FormData to prepare data for sending:
......
login = () => {
var formData = new FormData();
formData.append('username', 'react');
formData.append('password', '123');
fetch('http://......', {
method: 'POST',
body: formData
........

react-native fetch - request body - Unexpected EOF

in my react-native application, I'm trying to make fetch request with body. But, I get error message of unexpected EOF. Actually, the request is made, I mean I can see through backend logs that request is sent, whereas, right after the request, it shows error message.
Here is my fetch method.
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.json())
.then((responseJson) => {
console.log("SEND_SMS RESULT: ",responseJson);
})
.done();
here is the error screen I get.
I would say that it fails on this line: response.json()
Are you sure that your response is a valid JSON?
Try testing the response with Postman or add .catch(e => console.log(e)) before done();
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.text())
.then((responseJson) => {
const resposeJson2 = responseJson.length ? JSON.parse(responseJson) : {};
console.log("SEND_SMS RESULT: ",responseJson2);
})
.done();
Your server is returning null instead of error and unfortunately response.json() cant operate on null response
you can research briefly on it the keywords are "Handling null response from api"

AXIOS : Send Authorization header returns Error 401, Authorization Header missing

I came around this solution but this is not working for me.
Following is my code:
axios.post('http://myurl/api/login', {
email: 'john#doe.com',
password: '123456'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(response => {
if (response.data) {
this.AuthToken = response.data.token
console.log(this.AuthToken)
axios.get('http://myurl/userdetails/:uid', {
uid: 'D123'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': this.AuthToken
}
}).then(response => {
if (response.data) {
// this.AuthToken = response.data
console.log(response.data)
}
}).catch(error => {
console.log('User Data response Error: ' + error)
})
}
}).catch(error => {
console.log('Login Error: ' + error)
})
I'm getting token from the first POST Login API call. I used that toke to pass into another API call as Authentication token. But I get error: Missing Authorization Headers
Found the solution:
axios.defaults.headers.common['Authorization'] = this.AuthToken;
Try to add another header. "Access-Control-Allow-Headers" : "*".