Getting text in response instead of response body - chai

I am using chai to get response body. Instead, I always get my desired result in text. I have tried:
.post('xyz.com/server')
.set('Cookie', 'somevalue=1234')
.set('content-type', 'application/json')
When I print out my response object, I never get body. This is how my response looks like:
"header": {
"x-powered-by": "Express",
"access-control-allow-origin": "*",
"access-control-allow-headers": "Origin, X-Requested-With, Content-Type, Accept",
"access-control-allow-credentials": "true",
"access-control-allow-methods": "Content-Type",
"content-type": "application/json; charset=utf-8",
"content-length": "107",
"etag": "W/\"6b-rgYrpZXb7TdJm/JOuUivlL3U1fA\"",
"vary": "Accept-Encoding",
"date": "Wed, 31 Jan 2018 19:38:24 GMT",
"connection": "close"
},
"status": 200,
"text": "{\"err\":\"1006\",\"errDesc\":\"Sorry, your request could not be completed at this time. Please try again later.\"}"
}
I need that text to come in body. Thanks in advance
Edit:
The temporary solution is to use JSON.parse(res.text) which converts it into a JSON which I need from a response body. But if someone knows the solution to original problem, please post.

I have used a generic Serializing object that takes in a dynamic object and returns an HTTPResponseMessage.. Like this C# method:
public HttpResponseMessage ToJson(dynamic obj)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8);
return response;
}

Related

Sending MSXML2 request to the website in excel vba. User and password problem

I want to send a request to the website from excel vba. I have no business with the answer of the site, just send it :). but as far as i see in vba it redirects me to the user login page.
how can i do this request from excel vba
Option Explicit
Sub GetData()
Dim http As MSXML2.XMLHTTP60
Dim url As String
Set http = New MSXML2.XMLHTTP60
'url = "https://ws.samgaz.com.tr:10000/isEmriGrup/update/500__method=PUT&version=372&grup=101&tip=KesmeIhbarname&aciklama=19+May%C4%B1s&planlananGun=&_stIsEmri=&yetkiGrup=709&kullanicilar=995342164&_action_update=G%C3%BCncelle"
url = Sayfa1.[a2]
http.Open "GET", url, False
http.Send
Debug.Print http.responseText
End Sub
the codes I got from the chrome review of the request I want to make
fetch("https://ws.samgaz.com.tr:10000/isEmriGrup/update/500", {
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
"cache-control": "max-age=0",
"content-type": "application/x-www-form-urlencoded",
"sec-ch-ua": "\"Chromium\";v=\"106\", \"Google Chrome\";v=\"106\", \"Not;A=Brand\";v=\"99\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"cookie": "JSESSIONID=44C89F05EAAB847951061FE4B23F789C",
"Referer": "https://ws.samgaz.com.tr:10000/isEmriGrup/edit/500",
"Referrer-Policy": "strict-origin-when-cross-origin"
},
"body": "_method=PUT&version=372&grup=101&tip=KesmeIhbarname&aciklama=19+May%C4%B1s&planlananGun=
&_stIsEmri=&yetkiGrup=709&kullanicilar=995342164&_action_update=G%C3%BCncelle",
"method": "POST"
});
Identity login request screen looks like this
fetch("https://ws.samgaz.com.tr:10000/j_spring_security_check", {
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
"cache-control": "max-age=0",
"content-type": "application/x-www-form-urlencoded",
"sec-ch-ua": "\"Chromium\";v=\"106\", \"Google Chrome\";v=\"106\", \"Not;A=Brand\";v=\"99\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"cookie": "JSESSIONID=633796686F59D9EDAF8F6F97E22A81DF",
"Referer": "https://ws.samgaz.com.tr:10000/login/auth",
"Referrer-Policy": "strict-origin-when-cross-origin"
},
"body": "j_username=*******&j_password=*******",
"method": "POST"
});

flutter http post request showing status code 500 although its works in postman

**flutter**
As you can see below code of post method in which i pass static data for post through post API,
those data are work in postman but not in this method
Future addbuss() async {
var urlpost = "https://jcien.com/api/addBusinessReceived";
var responce = await http.post(urlpost,
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({
"user": "7",
"ch_id": "1",
"user_from": "9",
"entry_date": "2021-05-31",
"amount": "1234",
"business_type": "new",
"referral_type": "inside",
"remarks": "demoapii",
}));
print(responce.statusCode);
**statusCode**
status code showing error of 500
}
The error message is self-explanatory:
You must debug your API, the error is from there.
Check log server.
I think It might be because of
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
Use this instead
headers: {
'Content-Type': 'application/json'
},

React native throwing 406 "Not Acceptable" for android only

I have got zf3/laminas API configured to fetch JSON data. It is working fine in IOS or web simulator but doesn't work in android.
It throws:
Object {
"detail": "Unable to resolve Accept header to a representation",
"status": 406,
"title": "Not Acceptable",
"type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
}
This is the header zf3 sending to react:
Headers {
"map": Object {
"access-control-allow-headers": "Authorization, Origin, X-Requested-With, Content-Type:application/json, Accept:*",
"access-control-allow-methods": "PUT, GET, POST, PATCH, DELETE, OPTIONS",
"access-control-allow-origin": "http://localhost:4200",
"cache-control": "public, max-age=0",
"cf-cache-status": "DYNAMIC",
"cf-ray": "5ad7bbb47f45db28-KIX",
"cf-request-id": "03bab3a4ce0000db282798b200000001",
"connection": "keep-alive",
"content-type": "application/problem+json",
"date": "Sat, 04 Jul 2020 09:13:57 GMT",
"server": "cloudflare",
"vary": "Accept-Encoding,User-Agent",
"x-powered-by": "PHP/7.2.30",
},
}
My function in react:
async componentDidMount() {
try {
const call = await fetch(API_URL_INIT, [{'accept':'application/json', 'content-type':'application/json'}]);
console.warn(call.headers);//.get('Access-Control-Allow-Origin'));
const resp = await call.json();
} catch(err) {
this.setState({error: true});
console.log("Error fetching data-- ---------", err);
}
}
What am I doing wrong?
Ok, so so stupid. I had some syntax errors.
This is working:
const dictionaryApiCall = await fetch(
API_URL_INIT,
{
headers: { //add headers
'Accept': 'application/json',
'Content-type': 'application/json'
}
}
);
Hope this helps someone.

BigCommerce Create Shipment - no response

I am coding a API to create shipments on Big Commerce.
I am getting responses from the 'Get' URL's - I just can't seem to get the API to respond on the 'PUT'
I fired up a 'Web Responder' and it returns the following:
The tokens etc are moved for security.
Header:
{
"VERSION": "HTTP/1.1",
"CONNECTION": "close",
"ACCEPT-ENCODING": "gzip",
"CONTENT-TYPE": "application/json",
"AUTHORIZATION": "Bearer ---------------------",
"X-AUTH-CLIENT": "======================",
"X-AUTH-TOKEN": "=========================",
"ACCEPT": "application/json;",
"ACCEPT-CHARSET": "UTF-8;",
"USER-AGENT": "West Wind Internet Protocols 5.56",
"CACHE-CONTROL": "no-cache",
"COOKIE": "__cfduid=dfebfa0729eeaf50601b1fe187807c6fc1529278210; owner_token=cdc79c402c05c15d01ce0996dcc40654e3a0fe75a256eae3",
"CONTENT-LENGTH": "171"
}
The 'PUT' has:
PUT /b7ezoY2bqq2DKg0soyMy
{
"tracking_number": "PBT0000124",
"comments": "Shipped by PBT",
"order_address_id": 392,
"shipping_provider": "",
"items": [
{
"order_product_id": 1540,
"quantity": 1
}
]
}
As far as I can tell, all the details are correct. I just get no response. Please not this is a 'Desktop' application - not a Website.
Any clues?

Axios Request Does Not Return a Token

i'm trying to apply token for my request. So i tried to console.log the result of the request, and cannot find any token there inside the object array.
Object {
"config": Object {
"adapter": [Function xhrAdapter],
"data": "ktp=3578270708950002&member=199508070003",
"headers": Object {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
},
"maxContentLength": -1,
"method": "post",
"timeout": 0,
"transformRequest": Object {
"0": [Function transformRequest],
},
"transformResponse": Object {
"0": [Function transformResponse],
},
"url": "http://103.53.10.122/mobile/LoginCheck.php",
"validateStatus": [Function validateStatus],
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
},
"data": Array [
Object {
"status": "67457",
},
],
"headers": Object {
"connection": "keep-alive",
"content-type": "text/html; charset=UTF-8",
"date": "Fri, 22 Dec 2017 05:38:21 GMT",
"server": "nginx",
"transfer-encoding": "chunked",
"vary": "Accept-Encoding",
},
"request": XMLHttpRequest {
"DONE": 4,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"OPENED": 1,
"UNSENT": 0,
"_aborted": false,
"_cachedResponse": undefined,
"_hasError": false,
"_headers": Object {
"accept": "application/json, text/plain, */*",
"content-type": "application/x-www-form-urlencoded",
},
"_incrementalEvents": false,
"_lowerCaseResponseHeaders": Object {
"connection": "keep-alive",
"content-type": "text/html; charset=UTF-8",
"date": "Fri, 22 Dec 2017 05:38:21 GMT",
"server": "nginx",
"transfer-encoding": "chunked",
"vary": "Accept-Encoding",
},
"_method": "POST",
"_requestId": null,
"_response": "[{\"status\":\"67457\"}]",
"_responseType": "",
"_sent": true,
"_subscriptions": Array [],
"_timedOut": false,
"_trackingName": "unknown",
"_url": "http://103.53.10.122/mobile/LoginCheck.php",
"readyState": 4,
"responseHeaders": Object {
"Connection": "keep-alive",
"Content-Type": "text/html; charset=UTF-8",
"Date": "Fri, 22 Dec 2017 05:38:21 GMT",
"Server": "nginx",
"Transfer-Encoding": "chunked",
"Vary": "Accept-Encoding",
},
"responseURL": "http://103.53.10.122/mobile/LoginCheck.php",
"status": 200,
"timeout": 0,
"upload": XMLHttpRequestEventTarget {},
"withCredentials": true,
},
"status": 200,
"statusText": undefined,
}
Can someone point me how to add token to authenticate, because i'm still confuse about the concept even after reading it. So if i'm not mistaken, i should do the following in order:
Generate the token when user successfully login
Save the token in local storage
Use the token for each request (How does the backend check the validity of the token?)
Any help would be appreciated
Depending on the way the backend handles API requests you should either use axios.get and append the token to the URL or use axios.post and pass a object as body to the method with your token.
E.g.
axios.post('http://103.53.10.122/mobile/LoginCheck.php', {
username: "test",
password: "1234"
})
.then((res) => {
console.log(res);
/*
In this example I assume that res.data has the token returned from the backend
The res.data should look like this then:
{
token: "1234"
}
*/
let token = res.data.token;
AsyncStorage.setItem("token", token);
})
.catch((err) => {
console.log(err);
});
To use the token for each request save it in AsyncStorage for persistent storage or in the redux state if you are using redux.
On the server side you could generate a JSON web token which contains all data you need for authenticating the user and validating it with the data stored in a database. Due to the fact that you are using PHP I can recommend you this introduction to JSON web tokens in combination with PHP: https://www.sitepoint.com/php-authorization-jwt-json-web-tokens/