I am trying to open a server-sent-events connection on android in react native using XMLHttpRequest. My server does not see the attached authorization header. Any other headers that I attach to the request make it through. Here is my source code:
xhr = new XMLHttpRequest();
xhr.open("GET", "mydomain.com", true);
this._xhr.setRequestHeader("Accept", "text/event-stream");
this._xhr.setRequestHeader("Cache-Control", "no-cache");
this._xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
this._xhr.setRequestHeader("authorization", `Bearer: ${this.authorizationToken}`);
The value of the authorizationToken exists at runtime and is a normal jwt token. Using curl, I can successfully connect to my SSE server. However, it seems that the authorization token is stripped out of the request in react native. Is there a reason why this specific header is blocked? If I change the header key to authToken it is passed as expected. A hint may be related to this working on a localhost domain but not on production (real) domains. No fetch, no axios, I need to use XMLHttpRequest so I can establish a server-sent-events connection. Downstream shared code expects the presence of the authorization header. Here is what my server sees:
Request: {
url: '/testuser',
body: {},
params: {},
headers: {
host: 'mydomain.com',
deviceid: 'mydeviceid',
accept: 'text/event-stream',
'cache-control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'accept-encoding': 'gzip',
'user-agent': 'okhttp/4.9.2',
'x-forwarded-for': '',
'x-forwarded-proto': 'https',
'x-envoy-external-address': '',
'x-request-id': '',
'x-envoy-attempt-count': '1',
'x-forwarded-client-cert': '',
'x-b3-spanid': '',
'x-b3-parentspanid': '',
'x-b3-sampled': '0'
}
}
Any help on this issue would be greatly appreciated.
Tried to make an XMLHttpRequest with an authorization header, and the header was stripped out before reaching the server.
tried this one and it's working fine. try to remove true from open method
const Http = new XMLHttpRequest();
Http.open("GET", url)
Http.setRequestHeader('authorization', `Bearer: ehwrwhrkjewhgrkjewhregwjwgrjwgrjerjeg`)
Http.send();
console.log("Http =>>>>", Http)
output:-
{
"DONE": 4,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"OPENED": 1,
"UNSENT": 0,
"_aborted": false,
"_cachedResponse": undefined,
"_hasError": false,
"_headers": {
"authorization": "Bearer: ehwrwhrkjewhgrkjewhregwjwgrjwgrjerjeg"
},
"_incrementalEvents": true,
"_lowerCaseResponseHeaders": {},
"_method": "GET",
"_perfKey": "network_XMLHttpRequest_https://reqres.in/api/users?page=2",
"_performanceLogger": {
"_closed": false,
"_extras": {},
"_pointExtras": {},
"_points": {
"initializeCore_end": 8665333.465721,
"initializeCore_start": 8665252.249148
},
"_timespans": {
"network_XMLHttpRequest_http://localhost:8081/symbolicate": [Object],
"network_XMLHttpRequest_https://reqres.in/api/users?page=2": [Object]
}
},
"_requestId": null,
"_response": "",
"_responseType": "",
"_sent": true,
"_subscriptions": [{
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}],
"_timedOut": false,
"_trackingName": "unknown",
"_url": "https://reqres.in/api/users?page=2",
"readyState": 1,
"responseHeaders": undefined,
"status": 0,
"timeout": 0,
"upload": {},
"withCredentials": true
}
Related
I am working with the above issue that has had me stymied for hours on Android. I am using:
XMLHTTPRequest to upload an image file to my server. I have verified using document explorer in android that the image actually exists at the given uri.
I get xhr object as:
{"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted":
false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"accept":
"application/json", "authorization": "Bearer **********", "content-type": "multipart/form-data", "x-tenant": "EOG"},
"_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_requestId": null, "_response": "Unrecognized FormData part.", "_responseType": "",
"_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url":
"*************/uploadFile", "readyState": 4, "responseHeaders": undefined, "status": 0,
"timeout": 0, "upload": {}, "withCredentials": true}
I noticed in the above object: "_response": "Unrecognized FormData part."
My code looks like:
const {pic, kyc_document, kyc_identifier, kyc_expiry_date, ssn} = data;
let xhr = new XMLHttpRequest();
xhr.open(
'POST',
'https://**********/upload',
true,
);
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.setRequestHeader('x-tenant', 'EOG');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onerror = function (error) {
console.log(xhr);
console.log('ERROR -----------', error);
console.log(pic);
};
let formData = new FormData();
formData.append('kyc_type', 'identity');
formData.append('kyc_document', kyc_document);
formData.append('kyc_meta_data', {issuing_state: state});
formData.append('kyc_identifier', kyc_identifier);
formData.append('kyc_expiry_date', kyc_expiry_date);
formData.append('kyc_file', {
uri: pic.uri,
type: 'image/jpeg',
name: 'Id',
});
}
try {
xhr.send(formData);
} catch (e) {
console.log(e);
}
}
};
This is returning {"isTrusted": false}
The uri looks like "uri": "file:///data/user/0/com.mon.app/cache/Camera/e6c2ae90-a9a8-43aa-9e36-62c73a76f2ef.jpg"
my package details are:
"react": "16.11.0",
"react-native": "0.62.2",
I am trying to upload image to an API the iOS version is working good but there is problem in android, My code is bellow.
const uploadUri =
Platform.OS === 'ios'
? uploadImageFile.replace('file:', '')
: uploadImageFile;
// console.log(uploadUri);
const data = new FormData();
data.append('file', {
uri: uploadUri,
name: 'file',
type: 'image/jpg',
});
Axios.post(`${API.BASE_URL}/user/image`, data, {
headers: {
Authorization: token,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
setActivity(false);
setIsImageEdit(false);
console.log('success');
})
.catch((error) => {
setActivity(false);
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
setIsImageEdit(false);
});
The error response I get is
{"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"accept": "application/json, text/plain, */*", "authorization": "7aeb23f62bd748c39c9e8652eb1056e2"}, "_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey": "network_XMLHttpRequest_https://capi-test.beebl.io/user/image", "_requestId": null, "_response": "Could not retrieve file for uri /storage/emulated/0/Pictures/images/image-448777a5-1734-41f4-857e-a99d5239c279.jpg", "_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url": "https://capi-test.beebl.io/user/image", "readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, "withCredentials": true}
"_response": "Could not retrieve file for uri /storage/emulated/0/Pictures/images/image-448777a5-1734-41f4-857e-a99d5239c279.jpg"
I fixed it by adding
android:requestLegacyExternalStorage="true"
in AndroidManifest.xml
Hi i have self hosted parse server on digital ocean, it is sending notifications on iOS but not on android. my index.js file looks like this:
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://1.1.1.1"1/app_name',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: 'abc',
masterKey: 'def',
serverURL: 'http://1.1.1.1:1337/parse' || 'http://localhost:1337/parse',
verbose: true,
push: {
android:{
senderId: 'my FCM id',
apiKey: 'my FCM key'
},
ios: {
pfx: '1',
bundleId: '2',
production: true
}
}
});
when i send a push from the parse dashboard (also self hosted), this is the response i get with verbose:true:
"results": [
{
"objectId": "bNtZqwY8",
"pushTime": "2017-06-13T10:49:06.095Z",
"query": "{\"UniqueId\":\"c49de788ce\",\"deviceType\":{\"$in\":[\"android\"]}}",
"payload": "{\"alert\":\"Thank you for using my app.\"}",
"source": "rest",
"status": "succeeded",
"numSent": 0,
"pushHash": "266b6b637152b36040830",
"createdAt": "2017-06-13T10:49:06.095Z",
"updatedAt": "2017-06-13T10:49:06.214Z",
"numFailed": 15,
"failedPerType": {
"android": 15
},
"ACL": {}
},
{
"objectId": "rsYinvGG",
"pushTime": "2017-06-13T10:48:42.449Z",
"query": "{\"UniqueId\":\"7A0A-9AEA-5870FDEC42A3\"}",
"payload": "{\"alert\":\"one\",\"link_key\":1,\"sound\":\"default\"}",
"source": "rest",
"status": "succeeded",
"numSent": 2,
"pushHash": "246431e019c0357dcb180c7",
"createdAt": "2017-06-13T10:48:42.449Z",
"updatedAt": "2017-06-13T10:48:43.282Z",
"numFailed": 0,
"sentPerType": {
"ios": 2
},
"ACL": {}
},
When i send push on android from FCM, it works. Im really lost here with android push, can someone please point me in the right direction.
Here is the output from the log:
ESC[36mverboseESC[39m: REQUEST for [PUT] /parse/classes/_Installation /zKIp8LLOWr: {
"GCMSenderId":"diMV6Hm3j07dbqVPEsZRgqNzDo3YvA5zNdUmtO6Q4ka5ijRyyIRHiWCWOBVBDA22OIls-4bO06kxDPuOKFwJUZuMD3Xt41WuKUoOJwBlW7cKdqv9llj7Me0uiWFLWDwS7V",
"UniqueId": "a59020fff8ca30d00",
"appVersion": "2.3.3",
"objectId": "zKIp8LLOWr"
} method=PUT, url=/parse/classes/_Installation/zKIp8LLOWr, x-parse- app-display-version=2.3.3, x-parse-installation-id=29918e2f-8bbd-4ab7-975f-f854e1f43689, user-agent=Parse Android SDK 1.13.1 (com.mrfizzy/18) API Level 21, connection=Keep-Alive, accept-encoding=gzip, x-parse-os-version=5.0, x-parse-app-build-version=18, content-type=application/json, x-parse-client-key=, x-parse-client-version=a1.13.1, host=46.101.199.219:1337, content-length=245, x-parse-application-id=JHyfl9YhXCQ24r6J8ohdVlHLt1hfWhB4MF2jQAQn, GCMSenderId=diMV6HmLH3I:APA91bFQS4Sq9G5wlej07dbqVPEsZRgqNzDo3YvA5zNdUmtO6Q4ka5ijRyyIRHiWCWOBVBDA22OIls-4bO06kxDPuOKFwJUZuMD3Xt41WuKUoOJwBlW7cKdqv9llj7Me0uiWFLWDwS7V, UniqueId=a59020a48ca30d00, appVersion=2.3.3, objectId=zKIp8LLOWr
ESC[31merrorESC[39m: Error generating response. ParseError { code: 101, message: 'Object not found for update.' } code=101, message=Object not found for update.
[object Object]
It appears you're not assigning the Sender Id properly. You're passing an objectId that doesn't seem to be correct. Make sure you use ParseInstallation.getCurrentInstallation() when you set your GCM sender id rather than trying to get the installation by any other means.
http://parseplatform.org/Parse-SDK-Android/api/com/parse/ParseInstallation.html#getCurrentInstallation()
I am new in react native and I need to take information from JSON file asynchronously on change text in input field.
JSON:
{ "meta": {
"code": 200,
"api_version": "2.0.1.6.0",
"issue_date": "20160620"
},
"result": {
"total": 4,
"items": [{
"purpose_name": "Торгово-развлекательный комплекс",
"name": "Asia Park, торгово-развлекательный комплекс",
"full_name": "Алматы, Asia Park, торгово-развлекательный комплекс",
"id": "9430047374983999",
"building_name": "Asia Park, торгово-развлекательный комплекс",
"address_name": "Райымбека проспект, 514а / Саина, 516",
"type": "building"
}]
}
}
If it is a local JSON file you can just use require:
const data = require('./data.json');
console.log( data.result.items[0].purpose_name );
If it is a remote API request try fetch:
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => console.log( data.result.items[0].purpose_name ))
.catch(error => console.log(error));
If this file is local you may simply require it, it will get parsed automatically. If it is on some server you need to use the Fetch API.
I need to create a simple profile page . Whenever the user login successfully (s)he will be redirected to profile page , where his/her information along with photo will be displayed. i am trying below
Ext.define('casta.view.Intro', {
extend: 'Ext.tab.Panel',
xtype:'intro',
//need to call url and render json data to the template below
config: {
tpl: [
'<tpl for=".">',
'<div class="holder">',
'<div class="avatar"><img src="{profile_image_url}" /></div>',
'<div class="h-content">',
'<h2>{user}</h2>',
'<p>{text}</p>',
'</div>',
'</div>',
'</tpl>'
]
}
});
The json data is like below
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects": [{"date_joined": "2012-05-18T15:44:54", "first_name": "", "id": 1, "last_login": "2012-05-18T15:44:54", "last_name": "", "resource_uri": "/api/casta/user/1/", "username": "admin"}, {"date_joined": "2012-05-21T12:05:00", "first_name": "", "id": 29, "last_login": "2012-05-21T12:05:00", "last_name": "", "resource_uri": "/api/casta/user/29/", "username": "sumit"}]}
I need to call URL to return json and render that on the template.
Help me out :)
try some thing like this
http://www.sencha.com/forum/archive/index.php/t-117847.html
Ext.setup({
onReady: function() {
var itemInfo = new Ext.XTemplate(
'<ul>',
'<tpl for=".">',
'<li>{name}</li>',
'</tpl>',
'</ul>'
);
var content = new Ext.Panel({
fullscreen: true,
scroll: 'vertical',
tpl: itemInfo
});
Ext.util.JSONP.request({
url: 'http://demo.webfactory.mk/',
callbackKey: 'callback',
params: {
action: 'retrieve'
},
callback: function(data) {
data = data.result;
content.update(data);
}
});
}
});