React native fetch response bad characters - react-native

So i need to communicate with server. Here is my code
fetch('http://localhost:444/xml', {
method: 'POST',
headers: {
'STW-Authorization': 'Basic YmFybmk6YmFybmkxNTY=',
'Content-Type': 'text/xml',
},
})
.then(response => {
console.log(response.status)
return response.text()
})
.then(data => {
console.log(data)
})
And this prints badly encoded characters like �
Here is the result.
<?xml version="1.0" encoding="Windows-1250"?>
<rsp:responsePack version="2.0" id="" state="error" programVersion="12003.3 (21.11.2018)" ico="" note="Nebol n�jden� �iadny s�bor pre spracovanie." xmlns:rsp="http://www.stormware.cz/schema/version_2/response.xsd" xmlns:rdc="http://www.stormware.cz/schema/version_2/documentresponse.xsd" xmlns:typ="http://www.stormware.cz/schema/version_2/type.xsd" xmlns:lst="http://www.stormware.cz/schema/version_2/list.xsd" xmlns:lStk="http://www.stormware.cz/schema/version_2/list_stock.xsd" xmlns:lAdb="http://www.stormware.cz/schema/version_2/list_addBook.xsd" xmlns:acu="http://www.stormware.cz/schema/version_2/accountingunit.xsd" xmlns:inv="http://www.stormware.cz/schema/version_2/invoice.xsd" xmlns:vch="http://www.stormware.cz/schema/version_2/voucher.xsd" xmlns:int="http://www.stormware.cz/schema/version_2/intDoc.xsd" xmlns:stk="http://www.stormware.cz/schema/version_2/stock.xsd" xmlns:ord="http://www.stormware.cz/schema/version_2/order.xsd" xmlns:ofr="http://www.stormware.cz/schema/version_2/offer.xsd" xmlns:enq="http://www.stormware.cz/schema/version_2/enquiry.xsd" xmlns:vyd="http://www.stormware.cz/schema/version_2/vydejka.xsd" xmlns:pri="http://www.stormware.cz/schema/version_2/prijemka.xsd" xmlns:bal="http://www.stormware.cz/schema/version_2/balance.xsd" xmlns:pre="http://www.stormware.cz/schema/version_2/prevodka.xsd" xmlns:vyr="http://www.stormware.cz/schema/version_2/vyroba.xsd" xmlns:pro="http://www.stormware.cz/schema/version_2/prodejka.xsd" xmlns:con="http://www.stormware.cz/schema/version_2/contract.xsd" xmlns:adb="http://www.stormware.cz/schema/version_2/addressbook.xsd" xmlns:prm="http://www.stormware.cz/schema/version_2/parameter.xsd" xmlns:lCon="http://www.stormware.cz/schema/version_2/list_contract.xsd" xmlns:ctg="http://www.stormware.cz/schema/version_2/category.xsd" xmlns:ipm="http://www.stormware.cz/schema/version_2/intParam.xsd" xmlns:str="http://www.stormware.cz/schema/version_2/storage.xsd" xmlns:idp="http://www.stormware.cz/schema/version_2/individualPrice.xsd" xmlns:sup="http://www.stormware.cz/schema/version_2/supplier.xsd" xmlns:prn="http://www.stormware.cz/schema/version_2/print.xsd" xmlns:sEET="http://www.stormware.cz/schema/version_2/sendEET.xsd" xmlns:act="http://www.stormware.cz/schema/version_2/accountancy.xsd" xmlns:bnk="http://www.stormware.cz/schema/version_2/bank.xsd" xmlns:sto="http://www.stormware.cz/schema/version_2/store.xsd" xmlns:grs="http://www.stormware.cz/schema/version_2/groupStocks.xsd" xmlns:acp="http://www.stormware.cz/schema/version_2/actionPrice.xsd" xmlns:csh="http://www.stormware.cz/schema/version_2/cashRegister.xsd" xmlns:bka="http://www.stormware.cz/schema/version_2/bankAccount.xsd" xmlns:ilt="http://www.stormware.cz/schema/version_2/inventoryLists.xsd" xmlns:nms="http://www.stormware.cz/schema/version_2/numericalSeries.xsd" xmlns:pay="http://www.stormware.cz/schema/version_2/payment.xsd" xmlns:mKasa="http://www.stormware.cz/schema/version_2/mKasa.xsd" xmlns:gdp="http://www.stormware.cz/schema/version_2/GDPR.xsd" xmlns:ftr="http://www.stormware.cz/schema/version_2/filter.xsd"></rsp:responsePack>
The note text should be
Nebol nájdené žiadny súbor pre spracovanie.
Please help me found out the answer.

Related

Upload a file to an IPFS node from Google Apps Script

I'm trying to upload a file to an IPFS node using Google Apps Script (GAS) without success.
However, I was able to upload a file successfully using Postman. Unfortunately Postman only gives back the source code snippet closest to GAS as a JavaScript - Fetch code, which is not working as is in GAS.
In GAS, the authentication part is working and I know that because if I'm changing the bearer token, then I'm getting invalid credentials error instead of "Invalid request format".
Test code attached where I'm getting the "Invalid request format" error from the server.
For testing purpose, the file which needs to be uploaded, could be created on the fly with the script, but has to be one from Google Drive eventually.
function test() {
let myHeaders = {'Authorization': 'Bearer ...'};
let fileBlob = Utilities.newBlob('Hello!', 'text/plain', 'TestFile.txt');
let formdata = {'file': fileBlob,
'pinataMetadata': {'name': 'TestFileNewName.txt','keyvalues': {'MetaData1': 'Test1', 'MetaData2': 'Test2'}},
'pinataOptions': {'cidVersion': 0}};
let requestOptions = {
method: 'post',
headers: myHeaders,
papyload: formdata,
muteHttpExceptions: true
};
let url = "https://api.pinata.cloud/pinning/pinFileToIPFS";
let response = UrlFetchApp.fetch(url, requestOptions);
let responeText = JSON.parse(response.getContentText());
Logger.log(responeText);
}
If your access token of Bearer ... is the valid value for using the API, how about the following modification? From the official document, I thought that in the case of your formdata, the values of pinataMetadata and pinataOptions might be required to be the string type.
From:
let formdata = {'file': fileBlob,
'pinataMetadata': {'name': 'TestFileNewName.txt','keyvalues': {'MetaData1': 'Test1', 'MetaData2': 'Test2'}},
'pinataOptions': {'cidVersion': 0}};
To:
let formdata = {
'file': fileBlob,
'pinataMetadata': JSON.stringify({ 'name': 'TestFileNewName.txt', 'keyvalues': { 'MetaData1': 'Test1', 'MetaData2': 'Test2' } }),
'pinataOptions': JSON.stringify({ 'cidVersion': 0 })
};
And also, please modify papyload: formdata, to payload: formdata,. This has already been mentioned by
TheMaster's comment.
References:
Pin File
fetch(url, params)

POST Fetch request returns: grant_type was not specified

I had working code for fetching a access token with oauth, then I did a expo eject and now when I try to POST my auth code to get the access_token i receive response.
.then((auth_code) => {
let my_headers = new Headers()
my_headers.append('Authorization', `Basic ${base64_auth}`)
my_headers.append('Content-Type', 'application/x-www-form-urlencoded')
my_headers.append('Access-Control-Allow-Origin', '*')
my_headers.append('grant_type', 'authorization_code')
let urlencoded = new URLSearchParams()
urlencoded.append('code', auth_code)
urlencoded.append('grant_type', 'authorization_code') // <-- GRANT_TYPE HERE
let request_options = {
method: 'POST',
headers: my_headers,
body: urlencoded,
mode: 'cors'
}
console.log(request_options) // <--- OUTPUT BELOW
let url_with_params = `https://${url}/oauth/token/`
fetch(url_with_params, request_options)
.then((response) => response.json())
.then((json) => console.log(json)) // <--- OUTPUT BELOW
.then((json) => helpers.set_session_object('oauth_object', json))
.finally(() => set_loading(false))
.catch((error) => console.log('error', error))
})
.catch((error) => console.error(error))
console.log(request_options) outputs the following:
{method: "POST", headers: Headers, body: URLSearchParams, mode: "cors"}
body: URLSearchParams {_searchParams: Array(1)}
headers: Headers
map:
access-control-allow-origin: "*"
authorization: "Basic YXdheTprTkwpUmtWc2lWM2ppaCk3WDlmZXp3aSk="
content-type: "application/x-www-form-urlencoded"
grant_type: "authorization_code"
method: "POST"
mode: "cors"
and the json response outputs:
{"error": "invalid_request", "error_description": "The grant type was not specified in the request"}
Any idea why this is happening? I obviously have the grant_type declared right?
Looking at this I can see a couple of things that may not be quite right:
Remove the trailing backslash at the end of the OAuth token URL
Include a redirect_uri field, which is required in Authorization Code Grant messages
I suspect the first issue above is causing a redirect so that the POST to https://url/oauth/token/ becomes a GET to https://url/oauth/token.
Some similar issues are described in this post, and above all else I would aim to ensure that you can use an HTTP Proxy tool to view messages, which will make you much more productive at diagnosing this type of issue in future.
PROXY MOBILE SETUP
If it helps, my blog has some posts on proxy setup details:
Android HTTP Proxy Setup
iOS HTTP Proxy Setup

Getting Code 400 using Dialogflow on API request

this is my very first time using Dialogflow, so probably my mistake is very stupid.
here is my problem:
1) I created a sample agent "small-talk'.
2) I enabled the Webhook in the fulfilment section. I setup the URL of the web server making the request and the auth (username, password) of the that web server.
3) I uploaded a simple webpage on that web server with an API request that looks like this one below (this is the sample json referenced in their guide):
axios({
method: 'POST',
url: 'https://api.dialogflow.com/v1/query?v=20150910',
headers: {
'Authorization': 'Bearer ad7829588896432caa8940a291b66f84',
'Content-Type': 'application/json',
},
body: {
"contexts": [
"shop"
],
"lang": "en",
"query": "I need apples",
"sessionId": "12345",
"timezone": "America/New_York"
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
I keep getting this error:
Cannot parse json. Please validate your json. Code: 400"
The only thing I can thing of, is that I noticed that Dialogflow is now working with the API V2 enabled by default in the agent settings and it seems there is no selection to V1 available anymore. But maybe this has nothing to do with my problem.
Thanks in advance!
Solved it!
In the json request, instead of
body: {...}
I replaced it with
data: {...}
Probably it was obvious, but I am an absolute newbie on these things!
By the way, Google has shutdown Dialogflow V1 starting from 12th July 2021 as per this URL - https://cloud.google.com/dialogflow/docs/release-notes#June_15_2021
In case you are getting http response code 400 (bad request), it means that it is time to migrate :-)

Loading Data from Behance API in React Component

I am trying to load Behance project data via their API. Whether its localhost or prod, I am getting the following error --
Fetch API cannot load XXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Not sure how to solve for this.
My code in the Portfolio component below --
getPortfolio = () => {
const USER_ID = `XXX`,
PROJECT_ID = `XXX`,
API_KEY = `XXX`;
const BEHANCE_URL = `https://api.behance.net/v2/users/${USER_ID}/projects?client_id=${API_KEY}`;
console.log(BEHANCE_URL);
fetch(BEHANCE_URL, {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => {
return response.json();
}).then((responseData) => {
return responseData;
}).catch((err) => {
return err;
});
}
UPDATE: Instead of fetch, using jQuery ajax works. --
$.ajax({
url: BEHANCE_URL,
type: "get",
data: {projects: {}},
dataType: "jsonp"
}).done((response) => {
this.setState({
portfolioData: response['projects']
});
}).fail((error) => {
console.log("Ajax request fails")
console.log(error);
});
This seems to have do less with React and more with Behance. What you are getting is a CORS error as you probably figured out. The short explanation is that CORS is a security measure put in on the browser so that websites cannot request other websites from the browser to appear to be the second website. It is a safety measure in place to protect from some phishing attacks.
CORS can be disabled by the server (in this case, Behance) but they decide not to, for legitimate reasons.
Behance would probably allow you to make the request you are trying to make from a server instead. Once you do that, you will need to get the information from your server to your React application, and you will be good to go!

Meteor - how to submit an SSL certificate for *client* authentication in Meteor using a POST request?

EDIT: Updated Question here -
Based on # DoctorPangloss answer, I changed this to a server method. Below is the code. I'm not sure whether this is the right way to make the API call. The data returned is null from the server. Output is below the code.
Meteor.startup(function() {
var cert = Assets.getText('client-2048.p12');
Meteor.http.post(
"https://identitysso.betfair.com/api/certlogin",
{
headers:
{
"X-Application": "njhR7Q3ELfAZENlr",
"Content-Type": "application/x-www-form-urlencoded"
},
params: {
"username": "xxxx",
"password": "xxxx",
"pkcs12": cert,
"password": "xxxx"
}
},
function(error, result)
{
console.log(result);
}
);
});
Output after the API login call:
I20140529-16:38:37.220(5.5)? { statusCode: 404,
I20140529-16:38:37.220(5.5)? content: ' Lot of HTML data here '
I20140529-16:38:37.221(5.5)? headers:
I20140529-16:38:37.221(5.5)? { 'set-cookie':
I20140529-16:38:37.221(5.5)? [ 'wsid=7a5e0a81-e720-11e3-9af8-066b01d132ba; Domain=.betfair.com; Path=/',
I20140529-16:38:37.221(5.5)? 'vid=7a5e0a82-e720-11e3-9af8-066b01d132ba; Domain=.betfair.com; Expires=Sun, 26-May-2024 11:00:42 GMT; Path=/' ],
I20140529-16:38:37.222(5.5)? 'cache-control': 'no-cache,must-revalidate,no-store',
I20140529-16:38:37.222(5.5)? expires: '-1',
I20140529-16:38:37.222(5.5)? pragma: 'no-cache',
I20140529-16:38:37.222(5.5)? 'x-frame-options': 'DENY',
I20140529-16:38:37.222(5.5)? 'content-type': 'text/html;charset=UTF-8',
I20140529-16:38:37.222(5.5)? 'content-language': 'en-GB',
I20140529-16:38:37.222(5.5)? 'transfer-encoding': 'chunked',
I20140529-16:38:37.223(5.5)? date: 'Thu, 29 May 2014 11:00:42 GMT',
I20140529-16:38:37.223(5.5)? vary: 'Accept-Encoding' },
I20140529-16:38:37.223(5.5)? data: null }
Previous question:
A self-signed SSL cert needs to be sent to an external server to login. This is on localhost.
I'm sure I checked enough for an existing answer, but only this question comes close - Checking clients certificate in Meteor.
I'm trying to achieve BetFair's Non-interactive (Bot) login: https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Non-Interactive+%28bot%29+login
Here's the testcode on the client for a simple button click event:
Template.postsList.events({
'click .betfair': function() {
HTTP.call("POST", "https://identitysso.betfair.com/api/certlogin",
{headers: {
'X-Application' : 'njhR7Q3ELfAZENlr',
'Accept': 'application/json',
'Content-type' : 'application/x-www-form-urlencoded'
},
params: {
'username': 'xxxxxx',
'password': 'xxxxxx'
},
options: {
cert: fs.readFileSync('/Users/mmapp/client-2048.crt'),
requestCert: false,
rejectUnauthorized: false
}
},
function (error, result) {
if (!error) {
console.log("Looks like its logging in...");
}
});
}
});
I'm aware of the possible problems:
fs.readFileSync only works in npm/node.js?
Meteor needs something like nginx to handle SSL?
Should the above code be running from the server block of meteor?
Should Npm.require("fs") be used somewhere?
How do we achieve this login process in Meteor?
I'm a beginner and any help would be greatly appreciated! Thanks.
fs.readFileSync works neither in client or server. Checkout Assets.getText to read a certificate from the server.
If you want a client to provide a cert to BetFair, prompt for the file using an input and read the text data with Javascript. http://www.html5rocks.com/en/tutorials/file/dndfiles/ has a good overview on ways to read files in the browser. Note, some certificates have funky permissions to prevent you from, e.g., uploading the certificate to some browser.
You can process the result as follows:
function (error, result) {
// From their website, the result is something like {"sessionToken":"Zx8i4oigut5nc+l4L8qFb0DSxG+mwLn2t0AMGFxjrMJI=","loginStatus":"SUCCESS"}
if (result.data.loginStatus === "SUCCESS") {
Session.set("botFairSessionToken", result.data.sessionToken);
}
}
Depending on what you want to do, you should probably do this call on an Accounts.onCreateUser handler on the server. Instead of Session.set use Meteor.users.update({_id: this.userId}, {$set: {"services.botFair.sessionToken": result.data.sessionToken}});
// Handler for a call inside a server method body:
function (error, result) {
// From their website, the result is something like {"sessionToken":"Zx8i4oigut5nc+l4L8qFb0DSxG+mwLn2t0AMGFxjrMJI=","loginStatus":"SUCCESS"}
if (result.data.loginStatus === "SUCCESS") {
Meteor.users.update({_id: this.userId},
{$set: {"services.botFair.sessionToken": result.data.sessionToken}})
}
}
data is only populated if the response includes a Content-Type: application/json header. You write that content has a lot of HTML data so I assume the response is HTML. If so, then this is the correct behavior.
From the docs:
If the response headers indicate JSON content, this contains the body
of the document parsed as a JSON object.