React Native: Multipart body must have at least one part - android

I've seen "Multipart body must have at least one part" and I understand what it means, but I have no idea how to solve it.
We've got a React Native app, where it consumes a Swagger-autogenerated API client and at one point we make a POST request to an endpoint with no data. The endpoint does accept data though all the fields are optional and I should not send any data at that point.
On iOS, everything works perfect. On Android:
If I'm on React Native Debugger (standalone one) + Enable Network Inspect, the API request works perfectly.
If I'm on Vscode debugger, the request fails without even trying with the following error:
Multipart body must have at least one part.
Without being able to change the SDK (as it's autogenerated from Swagger, and the actual HTTP request is many middlewares deep), how can I get rid of this problem? It should be possible as the same HTTP request works on iOS.

Try to pass body as empty FormData in fetch function body parameter
See Example
var data = new FormData()
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: data
});

Related

react native android: TypeError: Network request failed

I'm using fetch command, running on Android emulator. When I used it with port "127.0.0.1" I got this error all the time no matter what type of request I was doing.
Then I changed it to http://10.0.2.2, and GET requests generally work, but I'm trying to make a POST request and get this error:
TypeError: Network request failed
My code:
const url = 'http://10.0.2.2:143'
const payload = {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
['x-access-token']: `Bearer ${token}`,
},
body,
}
const response = await fetch(url, payload)
On iOS everything's working fine so I don't think it's a problem with this code. What can I try to make it work on Android
The request doesn't even reach the server
if you are using android 9 or higher you should make requests with https , http has security problems

How do I get http content from a https website?

I get "Http failure response for https://www.google.com: 0 Unknown Error" when I request from Secured url.
I am trying to test my ionic/angular mobile app. When I tried with http requests I had problem with Android 9, but with Android 7 was working fine. Anyhow I need to set my backend to public https server. So now I'm testing with https request and none of 7 and 9 Android versions works.
I am using Angular 7 ,
"#ionic/angular": "^4.6.1",
"#ionic-native/core": "^5.0.0",
"rxjs": "~6.5.1"
I made these small functions in order to make my problem simpler.
inside my html file i have this code:
myFile.html
<ion-button
(click)="onStartTest()"
>Click me</ion-button>
<p id="testme"></p>
myFile.page.ts
onStartTest() {
this.taskService.onTest().subscribe(result => {
document.getElementById('testme').innerText = 'result ' + result;
console.log(result);
}, error => {
document.getElementById('testme').innerText = error.message;
console.log('Problem ', error.message);
});
}
myTask.service.ts
onTest() {
return this.http.get('https://www.google.com').pipe(
catchError(err => {
return throwError(err);
})
);
}
At first I tried my server's URL but I changed it to "https://www.google.com" just to verify that the backend is correct.
Also I have an interceptors.ts file that I am using it for authentication, but I am not logged in when I execute the onStartTest() function, but im gonna share it anw.
interceptors.ts
import {Injectable} from '#angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '#angular/common/http';
import {Observable} from 'rxjs';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('auth_token');
let newHeaders = req.headers;
if (token) {
console.log(token);
newHeaders = newHeaders.set('Authorization', 'Token ' + token);
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
} else {
newHeaders = newHeaders.set('Content-Type', 'application/json');
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
}
}
}
I think these are the necessary files to share for this problem.
I also tested the url of google with Postman just to be sure that I should get a status 200
I am also aware that there is an "add_header" directive (nginx) that adds 'Allow-access-control-origin' when the response code is 20x or 30x. According to my screenshot with Postman, google is responding with 200 status, but my app still gets status 0 error.
Ignore the first Error. It's a function I use with http when the app begins. Right now im testing https.
I tried superficially to use ionic-native library HTTP but my app totally crashed.
I also execute the command ionic serve --ssl but still nothing.
I read somewhere that for secured connection I need a certificate, but I understood that this is a server's work.
I tried to request from Dark Sky from Vanilla JavaScript and it works fine. So there is something wrong with angular/ionic side and not server's.
What am I missing? I really need to fix this problem soon!
I want to send a secured request to an https url and get the appropriate response.
Your main problem is that you are trying make an API to an unsecure call (http) location (http://192....../mobile/tasks) from a secure origin (https://localhost:8100).
This is clearly indicated in your error message and this is not allowed, and has been answered before
Your second problem is that, for testing purposes, you are trying to call a 3rd party https ressource from your website. This only works if the 3rd party ressource implement CORS, which is not the case for Google and api.darksky.net. Sending a GET request with Postman is useless, as Postman will not check for CORS headers before displaying the response. If you want to use Postman to check CORS, send an OPTIONS request to these ressources and you'll see that there are no CORS headers
So the answer is in MDN - CORS
For security reasons, browsers restrict cross-origin HTTP requests
initiated from scripts. For example, XMLHttpRequest and the Fetch API
follow the same-origin policy. This means that a web application using
those APIs can only request resources from the same origin the
application was loaded from, unless the response from other origins
includes the right CORS headers.
This means the back-end I was using needed some more configuration since I was using 'same-origin' policy script. I thought we had it because when we tried from the browser's console to fetch the request it was working fine, but on mobile it wasn't. We had a custom CORS configuration but we changed it to the django-cors-headers. Since we switched to django-cors-headers I could get correctly the response from HTTP and HTTPs requests.
The other answer and comments were really useful to focus to the right direction.

react native Fetch Network request failed on android

I'm trying to receive some simple json from mocky.
React native fetch function:
getMemberDomainList = async (name) => {
try {
let response = await fetch('https://5c9cc9ed3be4e30014a7d287.mockapi.io/api/domain', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
I have tested the address in chrome on windows, it returns the expected mock data. But when the function is called on my android phone I get this error
Error from remote debugger
...\node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:2348 TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:4337)
at XMLHttpRequest.dispatchEvent (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10760)
at XMLHttpRequest.setReadyState (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10511)
at XMLHttpRequest.__didCompleteResponse (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10343)
at ...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10449
at RCTDeviceEventEmitter.emit (...\Libraries\Components\DrawerAndroid\DrawerLayoutAndroid.android.js:11)
at MessageQueue.__callFunction (...\Libraries\ART\ReactNativeART.js:362)
at blob:http://localhost:8081/79251787-d190-4650-8040-23d091c08738:2334
at MessageQueue.__guard (...\Libraries\ART\ReactNativeART.js:312)
at MessageQueue.callFunctionReturnFlushedQueue (...\Libraries\ART\ReactNativeART.js:139)
I'm also running a WebView in my app, which is pointing to a web url, it loads perfectly so I am sure that the phone has internet permission and access etc.
In the latest android versions http requests are not allowed by default. Take a look at this post for further information about allowing http request: How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
Can't get mockapi.io to work. But the error is not persistent when using services such as:
https://jsonplaceholder.typicode.com/todos/1
Might not be an android or react native related problem after all. Also had issues with mockapi.io in postman, though it works fine in chrome.
If you are using emulator then check whether internet is working or not in this emulation using browser. If not check this: Android emulator not able to access the internet
I have also face this problem in emulator but when I generate a release app and install in a real device(andoid 9) then it works fine.
Please check backend response status.
If backend is sending contents using 205 status - 205 RESET CONTENT
Android system recognize it as an error - HTTP 205 had non-zero Content-Length: 25.
You can check the status code on postman.
So, in this case, the error should be fixed on backend.
It should send contents with 200 status code.

Fetch request giving HTML response only on Android in React Native app

I have a react native app and a normal fetch request for login is not behaving ideally for Android. I'm making a normal fetch request like this for Login--
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Now, this works totally fine on iOS and I get the JSON response which I'm supposed to. But on Android, I get an HTML response. And that HTML response is the web counterpart of the app. What could be the possible issues for this? since I'm told that issue is at my end and couldn't find anything. Also, I've checked it on Postman and it is working fine.

phonegap android ajax requests work for GET but not POST

Sending the below request in my phonegapp-ed android app works for GET but not POST.
With GET, everything works. With POST, the request goes through but the POST variables
are not coming through on the server side, and the server returns a
json response that says 'no parameters supplied.'
POST works fine from our mobile app - it is just the phonegap app where we are having an issue. What am i missing here??? Thanks in advance for any help you can provide!
I've tried changing the settings on the $.ajax call, the android manifest, everything I can think of.
Also, i'm using Android 2.2 and Phonegap 1.0
function goTeam(){
var dataString={lat:currentLocation.lat(),lng:currentLocation.lng()}; // this all works
$.ajax({
url: 'http://example.com/request/goTeam',
data: dataString,
dataType: 'json',
success:
function(b) {
if(b.status==1){ // woo hoo! it works
} else {
// the request went through but something was wrong - this is what i'm getting with POST
}
},
type: 'post', // works with GET, doesn't work with POST
error: function(jqXHR, textStatus, errorThrown){ alert("Noooo."); }
});
Are you trying cross-domain requests? Only GET requests work this way. You can use JSONP for this kind of request, but only GET works.
Phonegap does work with both GET and POST - cross-domain security issues do not apply. We had an idiosyncratic error our code that was preventing it from working. Phonegap is pretty awesome!

Categories

Resources