React native throwing 406 "Not Acceptable" for android only - react-native

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.

Related

React Native fetch for HTTP2 endpoint can not get body

I use React Native fetch to POST to endpoint which is AWS Lambda. By default it's HTTP/2. That works perfectly fine with curl:
% curl -X POST https://yyyyyy.execute-api.eu-central-1.amazonaws.com/Test/stripe_payment -H "x-api-key: xxxxx"
% {"errorCode": "OK", "client_secret": "zzzz"}
But the same from react native:
try {
response = await fetch(`${API_URL}/stripe_payment`, {
method: 'POST',
headers: {
'x-api-key': API_KEY,
},
});
}
catch (error) {
console.error(error);
}
console.log('API response', response);
Returns only Lambda headers, not body:
API response {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "dce744f2-6755-47e0-9a9d-74921ae64eba", "offset": 0, "size": 100}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "dce744f2-6755-47e0-9a9d-74921ae64eba", "offset": 0, "size": 100}}, "bodyUsed": false, "headers": {"map": {"content-length": "100", "content-type": "application/json", "date": "Fri, 11 Nov 2022 19:33:22 GMT", "x-amz-apigw-id": "bc58SFhsFiAFp1A=", "x-amzn-requestid": "fc157dbb-72d2-459e-a391-1ece0ff9680f", "x-amzn-trace-id": "Root=1-636ea381-0c40c8ec31bb9c4f52d0e44b;Sampled=0"}}, "ok": true, "status": 200, "statusText": "", "type": "default", "url": "https://yyyyyy.execute-api.eu-central-1.amazonaws.com/Test/stripe_payment"}
Above response is correct, but it contains only headers, no body.
I do suspect that is because of HTTP/2 binary protocol, looking at some discussions looks like react native did not support it correctly in the past.
Any hints ?
Thanks,
Mark
ok, looks like i have found the answer: https://github.com/facebook/react-native/issues/24520

Sending attribute from Request JSON in Response JSON is not working in Wiremock

I am working on wiremock POC and I am facing issues when I try to send an attribute from request payload in response payload.
Request Payload:
{
"work_order": "12345678"
}
Mapping file:
{
"request": {
"method": "POST",
"urlPath": "/transform"
},
"response": {
"status": 200,
"body": "{\"randomInteger\": \"{{randomValue type = 'UUID'}}\",\"CorrelationID\": \"{{{request.body}}}\"}",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"]
}
}
Response Payload:
{
"randomInteger": "d24ea3bf-36c0-40b8-b84b-b9268ee85f55",
"CorrelationID": "{
"work_order": "12345678"
}"
}
Above is working fine.
Now if I try to select the attribute value instead of entire body file, it is not working.
Mapping File:
{
"request": {
"method": "POST",
"urlPath": "/transform"
},
"response": {
"status": 200,
"body": "{\"randomInteger\": \"{{randomValue type = 'UUID'}}\",\"CorrelationID\": \"{{{request.body.work_order}}}\"}",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"]
}
}
Response Payload:
{"randomInteger": "e35e4d5f-b043-4770-b659-4131d313e002","CorrelationID": ""}

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 use Twitter search API with Application-only authentication

I am new to React Native and want to build an App that uses the Twitter search API to display Tweets. No need for User Authentication.
I've been struggling the last two nights to get this working and starting to get frustrated xD.
I've tried building the request using Fetch and XMLHttpRequest with no luck. Also I tried several packages enabling OAuth 2.0 which also didn't work. I have the feeling I'm over complicating things as all I want to do is use the Application-only authentication and use the Standard search API.
Does anyone out there please have a code snippet on how to do this in react native without any extra packages? Is it possible at all with "just" Fetch or XMLHttpRequest?
Thanks in advance
Edit: Here's my code so far
var base64 = require('base-64');
var credentials = encodeURIComponent(key) + ":" + encodeURIComponent(secret);
var encoded = new Buffer(credentials).toString('base64');
console.log(encoded);
fetch('https://api.twitter.com/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + encoded
},
body: {
'grant_type': 'client_credentials'
},
}).then((response) => console.log(response))
Here the response:
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "8dea4e53-7b39-4b78-b1a5-d7ef5a58de48",
"offset": 0,
"size": 114,
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "8dea4e53-7b39-4b78-b1a5-d7ef5a58de48",
"offset": 0,
"size": 114,
},
},
"headers": Headers {
"map": Object {
"cache-control": Array [
"public, max-age=0",
],
"content-disposition": Array [
"attachment; filename=json.json",
],
"content-type": Array [
"application/json;charset=utf-8",
],
"date": Array [
"Wed, 16 May 2018 16:55:48 GMT",
],
"expires": Array [
"Tue, 31 Mar 1981 05:00:00 GMT",
],
"last-modified": Array [
"Wed, 16 May 2018 16:55:48 GMT",
],
"ml": Array [
"A",
],
"server": Array [
"tsa_o",
],
"status": Array [
"403 Forbidden",
],
"strict-transport-security": Array [
"max-age=631138519",
],
"x-connection-hash": Array [
"b6dde5b876b934c8dcdb059ef0c400fa",
],
"x-content-type-options": Array [
"nosniff",
],
"x-frame-options": Array [
"DENY",
],
"x-response-time": Array [
"105",
],
"x-transaction": Array [
"0084737c0054c4dc",
],
"x-tsa-request-body-time": Array [
"26",
],
"x-twitter-response-tags": Array [
"BouncerCompliant",
],
"x-ua-compatible": Array [
"IE=edge,chrome=1",
],
"x-xss-protection": Array [
"1; mode=block; report=https://twitter.com/i/xss_report",
],
},
},
"ok": false,
"status": 403,
"statusText": undefined,
"type": "default",
"url": "https://api.twitter.com/oauth2/token",
}
So, I'm happy to report I got this working.
Main problem was the encoding of the Request Body.
Here"s the working code to authenticate and get a bearer token. Then using this token to use the search API:
_getBearer = () => {
var details = {
'grant_type': 'client_credentials'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
var key = "xxx";
var secret = "yyy";
var base64 = require('base-64');
var credentials = encodeURIComponent(key) + ":" + encodeURIComponent(secret);
var encoded = new Buffer(credentials).toString('base64');
console.log("Created encoded credentials: " + encoded);
fetch('https://api.twitter.com/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + encoded
},
body: formBody
}).then((response) => response.json())
.then((responseData) => {
bearerToken = responseData.access_token;
console.log("Got Bearer: " + responseData.access_token);
this._loadTweet();
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
_loadTweet = () => {
console.log("start load tweet");
fetch('https://api.twitter.com/1.1/search/tweets.json?q=love', {
method: 'GET',
headers: {
'Authorization': "Bearer " + bearerToken
}
}).then((response) => response.json())
.then((responseData) => {
console.log(JSON.stringify(responseData));
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
};
};

Krakenjs req.body parameters undefined

Not sure what happened, but req.body parameters are not showing up when I reach my controllers in a POST request.
I have turned off csrf in the middleware.json:
{
"middleware": {
"errorPages": {
"404": "errors/404",
"500": "errors/500",
"503": "errors/503"
},
"session": {
"module": "connect-redis",
"config": {
"ttl": 3600
},
"secret": "<some secret>"
},
"appsec": {
"csrf": false,
"csp": false,
"p3p": false,
"xframe": "SAMEORIGIN"
}
//
// "compiler": {
// "dust": "templates",
// "less": "css"
// },
//
// "static": {
// "srcRoot": "path:./public",
// "rootPath": "path:./.build"
// }
}
}
The controller code:
app.post('/user', function (req, res) {
res.format({
json: function () {
//extract the user from the req
try {
var user = new User();
user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.userName = req.body.userName;
user.password = req.body.password;
user.email = req.body.email;
//subsequent code omitted...
} catch (err) {
//handle error
}
}
})
});
The POST request looks like this:
POST /user HTTP/1.1 Host: localhost:8000 Cache-Control: no-cache
{ "firstName":"John", "lastName" : "Doe", "userName": "jdoe",
"password" : "somepassword", "email": "jdoe#jdoe.com" }
You have to set the headers in this instance to Content-Type application/json
POST /user HTTP/1.1
Host: localhost:8000
Content-Type: application/json
Cache-Control: no-cache
{ "firstName":"John", "lastName" : "Doe", "userName": "jdoe", "password" : "somepassword", "email": "jdoe#jdoe.com" }
What binarygiant said. If you're unable to set headers on your request, you can always serialize your JSON before posting it.