request formData to API, gets “Network Error” in axios while uploading image - axios

I am making a POST request to server to upload an image and sending formdata using axios in react-native. i am getting "Network Error". i also try fetch but nothing work.using react native image picker libeary for select image.in postman api working fine
formData.append('title', Title);
formData.append('class_id', selectClass._id)
formData.append('subject_id', checkSelected)
formData.append('teacher_id', userId)
formData.append('description', lecture);
formData.append('type', 'image');
var arr=[];
arr.push(imageSource)
arr.map((file,index)=>{
formData.append('file',{
uri:file.path,
type:file.type,
name:file.name
})
})
axios({
method: 'post',
url: URL + 'admin/assignment/create',
data: data,
headers: {
"content-type": "multipart/form-data",
'x-auth-token': token,
},
})
.then(function (response) {
//handle success
console.log('axios assigment post',response);
})
.catch(function (response) {
//handle error
console.log('axios assigment post',response);
});

Project keeps flipper java file under app > source > debug in react native > 0.62. There is an issue with Flipper Network that causes the problem in your case. If you remove the debug folder, you will not be able to debug Android with Flipper, so the best solution is upgrading Flipper version in android > gradle.properties to 0.46.0 that fixes the problem.
You can change it with this line
FLIPPER_VERSION=0.46.0
react-nativeandroid

The issue that I was facing which is close to what you are mentioning is that I was getting NetworkError when using image-picker and trying to upload the file using axios. It was working perfectly in iOS but not working in android.
This is how I solved the issue.
There are two independent issues at action here. Let’s say we get imageUri from image-picker, then we would use these following lines of code to upload from the frontend.
const formData = new FormData();
formData.append('image', {
uri : imageUri,
type: "image",
name: imageUri.split("/").pop()
});
The first issue is with the imageUri itself. If let’s say photo path is /user/.../path/to/file.jpg. Then file picker in android would give imageUri value as file:/user/.../path/to/file.jpg whereas file picker in iOS would give imageUri value as file:///user/.../path/to/file.jpg.
The solution for the first issue is to use file:// instead of file: in the formData in android.
The second issue is that we are not using proper mime-type. It is working fine on iOS but not on Android. What makes this worse is that the file-picker package gives the type of the file as “image” and it does not give proper mime-type.
The solution is to use proper mime-type in the formData in the field type. Ex: mime-type for .jpg file would be image/jpeg and for .png file would be image/png. We do not have to do this manually. Instead, you can use a very famous npm package called mime.
The final working solution is:
import mime from "mime";
const newImageUri = "file:///" + imageUri.split("file:/").join("");
const formData = new FormData();
formData.append('image', {
uri : newImageUri,
type: mime.getType(newImageUri),
name: newImageUri.split("/").pop()
});
I hope this helps to solve your problem :)

REACT NATIVE SOLUTION
If you are using Axios or Fetch in React Native and you got Network Error when uploading the file or data.
Try to commenting below line from the /android/app/src/main/java/com/{your_project}/MainApplication.java
its located around the 40-50 line
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
https://github.com/facebook/react-native/issues/28551

I faced the same issue. The following steps worked for me.
update FLIPPER_VERSION=0.52.0 latest
for formData code as below:
let formData = new FormData();
let file = {
uri: brand.uri,
type: 'multipart/form-data',
name: brand.uri
};
formdata.append('logo', file);
The type must be 'multipart/form-data' as the post header.

"react-native": "0.62.1",
"react": "16.11.0",
"axios": "^0.19.2",
weird solution i have to delete debug folder
in android ->app->source->debug
and restart the app again
its solve my problem. i think it's cache problem.

I had this problem and solve it via commenting the 43 line in
android/src/debug/.../.../ReactNativeFlipper.java
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
could you test it?

in my case, the solution was to change to
const headers = {
accept: 'application/json',
'content-type': 'multipart/form-data',
};

change this line: form_data.append('file', data);
To form_data.append('file', JSON.stringify(data));
from https://github.com/react-native-image-picker/react-native-image-picker/issues/798
You need to add this uesCleartextTraffic="true" to the AndroidManifest.xml file found inside the dir android/app/src/main/AndroidManifest.xml
<application ... android:usesCleartextTraffic="true"> Then, Because of issue with Flipper Network.
I commented initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
in this file /android/app/src/main/java/com/{your_project}/MainApplication.java
Also, commenting out line number 43 in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java
line43: builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

If using expo and expo-image-picker, then the problem is only with the image type and nothing else.
In the latest updates, they removed the bug related to path (as other answers mention to change the beginning of the path which was correct for the older versions).
Now to remove the problem, we need to change the type only and is mentioned by other answers to use mime which works fine;
import mime from 'mime'
const data = new FormData();
data.append('image', {
uri: image.uri,
name: image.uri.split('/').pop() // getting the text after the last slash which is the name of the image
type: mime.getType(image.uri) // image.type returns 'image' but mime.getType(image.uri) returns 'image/jpeg' or whatever is the type
})

In my case, after debbuging for a while, the issue was in nginx.
The image was "too big".
I Had to add annotations to the Kubernetes ingress:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/proxy-body-size: 20m
....
It was a bit tricky to debug since the request never got through the load balancer (nginx) to the Api service.
The "Network error" message didn't help a lot either.

I am using Expo SDK 42 (react-native v0.63). And I was using the expo-document-picker library to pick the documents & upload to server.
This is the code I am using to open the picker & get the metadata about the file.
const result = await DocumentPicker.getDocumentAsync({
type: 'image/*',
copyToCacheDirectory: false,
multiple: false,
});
if (result.type === 'success') {
const name_split = result.name.split('.');
const ext = name_split[name_split.length - 1];
// result.uri = 'file://' + result.uri;
result.type = helper.get_mime_type(ext);
delete result.size;
}
(You can write your function to get the mime type from the file extension or use some library from npm)
And this is the code I am using to upload the file to server:
const formdata = new FormData();
formdata.append('custom_param', 'value');
formdata.append('file', result); // 'result' is from previous code snippet
const headers = {
accept: 'application/json',
'content-type': 'multipart/form-data',
};
const opts = {
method: 'POST',
url: 'your backend endpoint',
headers: headers,
data: formdata,
};
return await axios.request(axiosopts);
The above code is the working code. I want to explain what I did wrong initially that was causing the Network Error in axios.
I had set copyToCacheDirectory to true initially and the uri I was getting in the result was in the format /data/path/to/file.jpeg. And I also tried appending file:// to beginning of the uri but it didn't work.
I then set copyToCacheDirectory to false and the uri I was getting in the result was in the format content://path/to/file.jpeg. And this didn't cause any Network Error in axios.

I have faced this error as well. I found out that I got this error because the file path is wrong and axios couldn't find the file. It is a weird error message when the uri is wrong though but that's what actually has happened. So double checking the uri of the file would fix the issue. Mainly consider file://.

I faced the same issue.
After capturing the photo wait for 10sec then start uploading. It worked for me.

Also got the same issue. I spent almost 4 days to find reason.
So in my case it was Content-Type: multipart/form-data. I forgot
indicate it. In Android it should be indicated explicitly...

After two days of searching for a solution, I found that the problem was in my rn-fetch-blob library, Changed it to in package.json dependencies
"rn-fetch-blob": "^0.12.0",
fix my Netowk issue and app crash on uploading. I am using
react-native-image-crop-picker

always send image and file in formdata in post api through axios in react js and react native
Blockquote

REACT NATIVE SOLUTION USING AXIOS
I face the same issue after upgrading react native cli project.
I'm using
"react-native": "0.70.6",
"react": "18.1.0",
"axios": "^1.1.3"
AND FLIPPER_VERSION=0.125.0
The below code solves my issue
const imageData = image;
const form = new FormData();
form.append("ProfileImage", {
type: imageData.mime,
uri: imageData.path,
name: imageData.path.split("/").pop(),
});
axios({
method: "put",
url: `${URL}/api/UploadPhoto`,
data: formData,
headers: {
"Content-Type": "multipart/form-data",
"cache-control": "no-cache",
},
processData: false,
contentType: false,
mimeType: "multipart/form-data",
});
For me, I didn't comment on any line from the /android/app/src/main/java/com/{your_project}/MainApplication.java
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
Also not changed FLIPPER_VERSION

Related

Failure in using axios to download pdf (Blank page)

...
PdfWriter.getInstance(document, outputStream); // outputstream from java
I successfully downloaded this pdf file by fetch api and postman, but failed by axios, even though the size was normal.
// I successfully downloaded this pdf file by fetch api and postman, but failed by axios, even though the size was normal(blank content).
axios({
url: `xxx`,
method: 'get',
responseType: 'arraybuffer'
}).then(resp => {
const url = window.URL.createObjectURL(new Blob([resp.data], {type:"application/pdf"}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'test.pdf');
document.body.appendChild(link);
link.click();
})
Can someone help me?
Remove or uninstall MockJS, and try it again!

File not uploading in server ionic3

I have a scenario where I am uploading a image file from my local drive (type jpeg or png) to an API endpoint using ionic. Here is my code below :
fileupload.html -->
//---------------------------------------------------
<ion-item>
<ion-input type="file" accept="image/*" (change)="changeListener($event)"> </ion-input>
</ion-item>
fileupload.ts -->
changeListener($event):void{
this.file=$event.target.files[0];
console.log(this.file);
console.log("upload...");
let regData={"file":this.file};
console.log("REGDATAA"+JSON.stringify(regData));
this.jira.postAttachment("PM-3",regData).subscribe(dataa=>{
console.log(dataa);
});
}
provider.ts -->
public postAttachment(key,data):Observable<any>{
console.log(JSON.stringify(data))
return this.http.post(this.api+'/issue/'+key+'/attachments',JSON.stringify(data),{
headers: new HttpHeaders()
.append('Authorization', `Basic ${this.auth.getAuthString()}`)
.append('Content-Type','multipart/form-data';boundary="-------xe3rtyhrfds")
.append("X-Atlassian-Token", "no-check")
.append("User-Agent", "xx")
});
}
every time I send the file it doesn't take the path and sends an empty response, here is the error below.
//----------------------------------------------------
[object File]: {lastModifiedDate: [date] Fri Sep 21 2018 17:42:46 GMT+0530 (India Standard Time), name: "download.jpg", size: 5056, type: "image/jpeg", webkitRelativePath: ""}
upload...
ion-dev.js (157,11)
REGDATAA{"file":{}}
ion-dev.js (157,11)
{"file":{}}
ion-dev.js (157,11)
ERROR [object Object]
I have resolved CORS issue and there is no problem with the same.
When I send the same response using postman it succeeds here is what I send in Postman.
Form-data
key - "file" (type file) value - "/path/to/my/file"
Headers
Content-type - application/json
x-attlassian token - no-check
Can somebody advice what is going wrong here.
Use FormData to upload file.
fileupload.ts
changeListener(event) {
const fd = new FormData();
this.file = event.target.files[0];
fd.append('file', this.file, this.file.name);
this.jira.postAttachment("PM-3",fd)
.subscribe(data => {
console.log(data);
});
}
provider.ts
postAttachment(key, fd): Observable<any> {
const httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'multipart/form-data' },
{ 'Authorization': `Basic ${this.auth.getAuthString()}` })
};
return this.http.post(this.api+'/issue/'+key+'/attachments', fd, httpOptions);
}
Your have to change the content type from application/json to multipart/form-data. You are sending an image, not a json-file.
Best way is to encode your image to base64 and send it. Everything depends about what your server needs.
or you can try this.
const body = file;
const headers = new Headers({'Content-Type': 'image/jpg'});
return this.http.post(this.api+'/issue/'+key+'/attachments, body, {headers: headers}). ...
For an issue on AngularJS what ended up working is (might a similar aproach help you too) :
make a hidden input de type file
set it's value in the changeListener function
make the file send from there afterwards
The reason being some built in propertie of the file input let's its value be recognised as File/Blob instead of the path many "complex" components use.
Also send it as multipart file as mentioned before.

Service in vue2JS - error in created hook

I'm new to vue2JS and currently I am trying to create my very first service in vue2 ever.
I've created basic file api.js with this code:
import axios from 'axios';
export default () => {
return axios.create({
baseURL: 'http://localhost:8080/',
timeout: 10000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
}
Code above is basic axios configuration which will be used in every service across entire app.
I import this file into my service:
import api from '../api.js';
export default {
getLatest () {
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`, {
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
}
Code above is responsible for making http request to backend rest API which give JSON in response.
And then finally I want to use this service inside my component <script></script> tags:
<script>
import { getLatest } from '../../../services/articles/getLatest';
export default {
data () {
return {
articles: []
}
},
created () {
const getLatestService = new getLatest();
console.log(getLatestService);
}
}
</script>
Here I want to execute code from service and actually execute this http request then save response in getLatestService constant and then console.log it and I should be able to see JSON in my browser console.
This doesn't work and give me this error in chrome console:
[Vue warn]: Error in created hook: "TypeError: WEBPACK_IMPORTED_MODULE_0__services_articles_getLatest.a is not a constructor"
And this error in command line:
39:35-44 "export 'getLatest' was not found in '../../../services/articles/getLatest'
Please help me to solve this problem. Additionally I want to refactor my code from service (second one) to use async await but I just can't find good example which would show me way to accomplish that.
EDIT 22.11.17
I added error which show in command line and { } when importing in component. I still didn't solve the problem.
EDIT 24.11.17
Looking for an answer I add more explanation of code I've posted and screenshot of files structure if maybe it can help.
I have check your code and what i can see is, in your api.js you have used
baseURL: 'http://localhost:8080/',
and in your service file
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`
In your service file you have not define your localhost port, i think it should be like
return api().get(http://localhost:8080/obiezaca/ob_serwer/api/article/getLatest.php
If above is not an your issue then you should try
const getLatestService = getLatest();
Because getLatest() is a function and not an object.
This might solve your error issue.

how to set basic authorization header for GET service in sapui5?

Can I get a sample code to set basic authorization as header along with other headers ( like x-csrf-token : fetch) in eclipse ?
You can do something like this with jQuery (which is of course included with UI5) for basic authentication:
function ajaxBeforeSend(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + password));
}
$.ajax({
type: "GET",
url: url,
dataType: "json",
beforeSend: function(xhr) {
ajaxBeforeSend(xhr);
}
}).done(function(data) { /* do something */ }
This is what I've used in some developments and it works well. You can set other headers this way as well.
See http://www.w3schools.com/jsref/met_win_btoa.asp for details on btoa() which base64 encodes the user:pass string.
Your question says: "in eclipse". I don't know what that means as the javascript will work regardless of what editor you use.
Here's the jQuery doco which describes the method used above: http://api.jquery.com/jQuery.ajax/.
(Watch out for CORS issues if service is not on the same host as your app. For CORS I find you also need to add xhr.withCredentials = true; inside the above ajaxBeforeSend() function.)

MVC + Extjs + IIS6 + Wildcard Mapping = Post Form resulting in 302 object moved

Everything seems to work fine until i want to submit the form and update the database.
Wildcard mapping works on requests like "/navigation/edit/1", but when i submit the form as:
var ajaxPost = function(Url, Params) {
Ext.Ajax.request({
url: Url,
params: Params,
method: 'POST',
async: false,
scope: this
});
};
it says "200 bad response: syntax error" and in firebug there is "Failed to load source for: http://.../Navigation/edit/1".
Any help?
Perhaps its a syntax error: try
params: {"sendparams": Params}
it turns out there was a urlrewrite rule for some other web site corrupting my requests.