I have researched this online but nothing seems like the code I have.
I am trying to work with firebase functions with both my android and iOS apps. I followed a tutorial and it worked fine in Android because it was done in Android but I want to do the same in iOS.
I was told that Alamofire, comparable to OkHttp in Android, was the way to go but I am not sure how to take the code I have in android and put it in SWIFT code so that It does the same thing.
Any assistance would be greatly appreciated.
Code that was used in Android
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
ProgressDialog progress;
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-myapp.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
EDIT - Conversion
This is what I was able to convert to along with the code submitted by #emrepun:
// HTTP Request .... (firebase functions)
MEDIA_TYPE.setValue("application/jston", forHTTPHeaderField: "Content-Type")
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"]
Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let value):
// you fall here once you get 200 success code, because you use .validate() when you make call.
print(value)
// parse your JSON here.
let parameters : [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
let postData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(error.localizedDescription)
} else {
print("Error: couldn't complete the transaction")
print(error.localizedDescription)
}
}
}
You can make a network request similar to your Java version with Alamofire as given below. You should also learn about how to parse JSON with swift. You might want to look at Codable, which makes it easy to parse JSON. Or you can try a framework called "SwiftyJSON", which is handy to handle json requests as well.
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"
]
Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let value):
// you fall here once you get 200 success code, because you use .validate() when you make call.
print(value) // parse your JSON here.
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(error.localizedDescription)
} else {
print("Error: couldn't complete the transaction")
print(error.localizedDescription)
}
}
}
Related
I am setting up a payout process for a driver in my app with Firebase Cloud Functions and Paypal. The url to be posted is the url of the actual cloud function in Firebase:
https://us-central1-ryyde-sj.cloudfunctions.net/payout
When trying to send an HTTP Post Request, it doesn't seem to be working. See the payoutRequest() and the Response code below:
payoutRequest()
let email = txtPayoutEmail.text!
let uid = self.uid!
// Prepare URL:
let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object:
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Headers
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Your Token", forHTTPHeaderField: "Authorization")
request.setValue("no-cache", forHTTPHeaderField: "cache-control")
print("request = \(request)")
// HTTP Request Parameters which will be sent in HTTP Request Body:
let postString = "uid=\(uid)&email=\(email)"
print("postString = \(postString)")
// Set HTTP Request Body
request.httpBody = postString.data(using: String.Encoding.utf8)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in
print("data: \(String(describing: data))")
print("response: \(String(describing: response))")
print("error: \(String(describing: error))")
if let response = response as? HTTPURLResponse {
// Read all HTTP Response Headers
print("All headers: \(response.allHeaderFields)")
// Read a specific HTTP Response Header by name
if #available(iOS 13.0, *) {
print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
} else {
// Fallback on earlier versions
}
}
// Check for Errors
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string: \(dataString)")
}
}
task.resume()
Response
request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
postString = uid=kv8JRVBwAfS1tgD04lNeM9esVzI2&email=myiosapp#me.com
data: Optional(138 bytes)
response: Optional(<NSHTTPURLResponse: 0x6000037d1c20> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 400, Headers {
"Content-Length" = (
138
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Thu, 17 Sep 2020 01:00:50 GMT"
);
Server = (
"Google Frontend"
);
"alt-svc" = (
"h3-Q050=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"content-security-policy" = (
"default-src 'none'"
);
"function-execution-id" = (
cmrwbktlroxl
);
"x-cloud-trace-context" = (
"a85aaacd578e60690581aa64ead13b23;o=1"
);
"x-content-type-options" = (
nosniff
);
"x-powered-by" = (
Express
);
} })
error: nil
All headers: [AnyHashable("content-security-policy"): default-src 'none',
AnyHashable("Date"): Thu, 17 Sep 2020 01:00:50 GMT, AnyHashable("alt-svc"): h3-Q050=":443";
ma=2592000,h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-
T050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443";
ma=2592000; v="46,43", AnyHashable("Content-Type"): text/html; charset=utf-8,
AnyHashable("Content-Length"): 138, AnyHashable("x-cloud-trace-context"):
a85aaacd578e60690581aa64ead13b23;o=1, AnyHashable("Server"): Google Frontend,
AnyHashable("x-powered-by"): Express, AnyHashable("x-content-type-options"): nosniff,
AnyHashable("function-execution-id"): cmrwbktlroxl]
Specific header: text/html; charset=utf-8
Response data string: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Bad Request</pre>
</body>
</html>
If the request is successful, then it would show up in the PayPal Notifications for PayPal Sandbox at the below link, but it isn't.
PayPal developer notifications link
I don't have much experience in PayPal HTTP requests.
I have done the same thing as I am trying to do here but in Android and it works perfectly so I know this should work, other than the Post Request (I tried using examples online to match what i had for the Android app)
Edit
updated payoutRequest():
Code surrounded in ** ** is new code
let email = txtPayoutEmail.text!
let uid = self.uid!
// Prepare URL:
let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object:
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Headers
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Your Token", forHTTPHeaderField: "Authorization")
request.setValue("no-cache", forHTTPHeaderField: "cache-control")
print("request = \(request)")
// HTTP Request Parameters which will be sent in HTTP Request Body:
**let body = ["uid": uid, "email": email]**
print("body = \(body)")
// Set HTTP Request Body
**request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])**
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in
print("data: \(String(describing: data))")
print("response: \(String(describing: response))")
print("error: \(String(describing: error))")
if let response = response as? HTTPURLResponse {
// Read all HTTP Response Headers
print("All headers: \(response.allHeaderFields)")
// Read a specific HTTP Response Header by name
if #available(iOS 13.0, *) {
print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
} else {
// Fallback on earlier versions
}
}
// Check for Errors
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string: \(dataString)")
}
}
task.resume()
Response:
request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
body = ["uid": "kv8JRVBwAfS1tgD04lNeM9esVzI2", "email": "driver#ryyde.com"]
data: Optional(0 bytes)
response: Optional(<NSHTTPURLResponse: 0x600001f0d6a0> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 200, Headers {
"Content-Length" = (
0
);
"Content-Type" = (
"text/html"
);
Date = (
"Thu, 17 Sep 2020 04:41:29 GMT"
);
Server = (
"Google Frontend"
);
"alt-svc" = (
"h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"function-execution-id" = (
cmrwtq89fdsr
);
"x-cloud-trace-context" = (
"f3fe884ca8499e7a10c7081ce222876e;o=1"
);
"x-powered-by" = (
Express
);
} })
error: nil
All headers: [AnyHashable("Content-Length"): 0, AnyHashable("x-cloud-trace-context"): f3fe884ca8499e7a10c7081ce222876e;o=1, AnyHashable("Server"): Google Frontend, AnyHashable("x-powered-by"): Express, AnyHashable("function-execution-id"): cmrwtq89fdsr, AnyHashable("alt-svc"): h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43", AnyHashable("Date"): Thu, 17 Sep 2020 04:41:29 GMT, AnyHashable("Content-Type"): text/html]
Specific header: text/html
Response data string:
EDIT 2
When I run my code, I check the function logs in firebase/functions (read from bottom up - seems to go ok with the function activity)
EDIT 3 - Charles Session results
URL https://us-central1-ryyde-sj.cloudfunctions.net Status Sending
request body… Notes Transaction began prior to session being cleared,
body content transmitted before the session clear has not been
captured Response Code 200 Connection established Protocol HTTP/1.1
TLS TLSv1.2 (TLS_AES_128_GCM_SHA256) Protocol TLSv1.2 Session
Resumed Yes Cipher Suite TLS_AES_128_GCM_SHA256 ALPN - Client
Certificates - Server Certificates - Extensions Method CONNECT Kept
Alive No Content-Type Client Address 127.0.0.1:57209 Remote
Address us-central1-ryyde-sj.cloudfunctions.net/216.239.36.54:443
Tags - Connection WebSockets - Timing Size Request 1.77 KB (1,817
bytes) Response 1.35 KB (1,379 bytes)
EDIT 4 - Android code
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-ryyde-sj.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
try this:
let body = ["uid": uid,
"email": email]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
From my research, there isn't much help translating Android code to Swift code. With some help, we were able to translate or convert some of the code but it's not quite finished. When I run the code, I get an error:
Response could not be serialized, input data was nil or zero length.
responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Android code needing converting to Swift code:
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
ProgressDialog progress;
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-myapp.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
Swift code used from the above Android code:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"]
Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let value):
// you fall here once you get 200 success code, because you use .validate() when you make call.
print(value)
// parse your JSON here.
let parameters : [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
let postData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(error.localizedDescription)
} else {
print("Error: couldn't complete the transaction")
print(error.localizedDescription)
}
}
}
How can I convert the Android code into the Swift code or discover what it is I am doing wrong? This code is used to post to the function I have created for Firebase.
Edit
With the help of supplied code in this post, I was able to come up with this code but it is still coming up with the same error:
===========Error===========
Error Code: 4
Error Messsage: Response could not be serialized, input data was nil or zero length.
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
updated swift code
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"]
let params : [String: Any] = [
"uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("Success with JSON: \(JSON)")
if (response.result.value as? [String:AnyObject]) != nil {
// Access your response here
print(response.result.value!)
}
break
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(print("Request failed with error: \(error.localizedDescription)"))
} else {
print("Error: couldn't complete the transaction")
print("\n\n===========Error===========")
print("Error Code: \(error._code)")
print("Error Messsage: \(error.localizedDescription)")
}
}
print("response \(response)")
}
EDIT #2
I edited my method:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"cache-control": "no-cache",
"Authorization": "Your Token",
"Content-Type": "application/json"]
let parameters : [String: Any] = [
"uid": uid,
"email": self.paypalEmailText.text!
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200..<600).responseJSON { (response) in
print("Request: \(String(describing: response.request))") // original url request
print("Result: \(response.result)") // response serialization result
if response.response?.statusCode == 200 {
print("Success with JSON: \(String(describing: response.result.value))")
} else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}
print("response \(response)")
}
The response and print outs are:
Request: Optional(https://us-central1-myapp.cloudfunctions.net/payout)
Result: FAILURE
Success with JSON: nil
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Keep in mind, in my url, my app is not called "myapp" it is just there for protection.
I think there are two issues in the code:
In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).
If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.
What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:
let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)
Try it out and see if it works.
So I'd do it like this here:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"
]
Alamofire.request(url,
method: .get,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: \(JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: \(error)")
}
}
In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.
I have this node.js code in my server side app:
app.post('/upload',function (req,resp) {
console.log(req);
var email=req.headers['email']
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null,'uploads/')
},
filename: function (req, file, cb) {
cb(null,"asdsad"+".jpg")
}
})
var upload = multer({ storage: storage }).single('propic')
upload(req, resp, function (err) {
if (err) {
throw err
}
resp.setHeader('Content-Type', 'application/json');
resp.send({status:true})
})
})
I want to send a bitmap in client side (Android) to server.
I used the okhttp library and I want to create form-data.
How can I do that?
You must send File to your server instead of bitmap and must use POST method to handle the request to Server side.
and write this codes to send your file into the server:
public class UploadService {
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
public void uploadImage(File image, String imageName) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", imageName, RequestBody.create(MEDIA_TYPE_PNG, image))
.build();
Request request = new Request.Builder().url("http://localhost:8080/v1/upload")
.post(requestBody).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
}
}
fetch() has been working fine on both iOS and Android until a month ago. I found out that when the response is long it would throw Network request failed error:
Network request failed
onerror
whatwg-fetch.js:504:29
dispatchEvent
event-target.js:172:43
setReadyState
XMLHttpRequest.js:576:29
__didCompleteResponse
XMLHttpRequest.js:392:25
<unknown>
XMLHttpRequest.js:505:8
emit
EventEmitter.js:191:12
__callFunction
MessageQueue.js:344:47
<unknown>
MessageQueue.js:107:26
__guard
MessageQueue.js:291:8
callFunctionReturnFlushedQueue
MessageQueue.js:106:17
This is how I set up fetch requests:
const URLENCODED_HEADER = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
async function getToken() {
try {
let response = await fetch(SERVER_URL+'/secure/token', {
credentials: 'include'
});
let responseJson = await response.json();
return responseJson.result
} catch(error) {
throw error;
}
}
async function doLogin(secureInfo) {
formBody = encodeParameters(secureInfo)
try {
let response = await fetch(SERVER_URL+'/user/login', {
method: "POST",
headers: URLENCODED_HEADER,
body: formBody,
credentials: 'include'
});
let responseJson = await response.json();
return responseJson;
} catch(error) {
console.error(error);
throw error;
}
}
Here are some responses that I was able to get back successfully:
1.
err_no: 0
result: BVV7IZVLOYgROXXc
2.
err_no:0
result:{
login_id:xxxx#gmail.com
user_name:""
email: xxx#gmail.com
user_id:11
login_type:1
}
However other longer responses, such as the one below, caused "Network request failed":
{
"err_no":0,
"result":[
{
"article_id":299,
"user_id":11,
"title":"society",
"content":"",
"text_content":"\n",
"tags":"[\"Society\"]",
"used_articles":"{}",
"citation_text":"",
"prompt":"",
"alternative_title":"",
"alternative_prompt":"",
"alternative_cnt":0,
"image_url":"",
"created":"2018-07-26 18:28:17",
"update_time":"2018-07-26 18:28:27"
}
]
}
(logged from web platform)
What could cause this and how should I fix it?
I have a link in the back-end, so I fetch a post request to that link and receive a response. When I alert that response it gives a body init and body text in which I receive datas I need. Everything is good. But..
When I enable remote debugging and console.log that response, it gives body init and body blob (and both are empty). It stucks when I eneble debugging..
Thanks for attention ))
My code:
logIn = async (username, password) => {
// alert(`username : ${username}\n password : ${password}`);
let loginFormData = new FormData();
loginFormData.append('LoginForm[username]', username);
loginFormData.append('LoginForm[password]', password);
loginFormData.append('MacAddress', '111');
loginFormData.append('loginType', 'mobile');
try {
fetch('http://192.168.2.115/araqich_client/general/default/logout', {
method: 'POST',
body: loginFormData
});
let request = fetch('http://192.168.2.115/araqich_client/general/default/login', {
method: 'POST',
body: loginFormData
});
let loginResponseJson = await request;
if (loginResponseJson && loginResponseJson != null ) {
// let loginResponse = JSON.parse(loginResponseJson._bodyInit);
alert(JSON.stringify(loginResponseJson._bodyInit));
let status = loginResponse.status;
if (status) {
let SyncFormData = new FormData();
let accessToken = loginResponse.ACCESS_TOKEN;
SyncFormData.append('ACCESS_TOKEN', accessToken);
SyncFormData.append('MacAddress', '111');
SyncFormData.append('loginType', 'mobile');
let syncRequest = fetch('http://192.168.2.115/araqich_client/mobile/defaultA/syncAndroid', {
method: 'POST',
body: SyncFormData
});
let syncResponseJson = await syncRequest;
if (syncResponseJson && syncResponseJson != null) {
let syncResponse = JSON.parse(syncResponseJson._bodyInit);
let status = syncResponse.status;
if (!status) {
alert('Sorry(( something went wrong...');
} else {
alert('Life is good)))');
}
}
} else {
alert('else1')
}
} else {
alert('else')
}
} catch (error) {
alert(error);
}
}
Instead of using console.log statements, I'd advise using your debugger.