A post method is working fine with Postman but not working in react native and getting error code 400. The api working from asp rest api.
I have tried this code.
const formData = new FormData();
formData.append("file", {
uri: imageUri,
name: stdAdmNo.replaceAll("/", ""),
fileName: stdAdmNo.replaceAll("/", ""),
type: "image/jpg",
});
console.log("image detail", formData);
let url = url;
try {
axios({
method: "post",
url: url,
data: formData,
headers: {
"Content-Type": "multipart/form-data",
},
})
.then(() => {
Alert.alert("Profile picture is successfully saved.");
})
.catch((error) => {
console.log(error);
});
} catch (e) {
console.log(e);
}
I am trying to send an object from react to express server using node.js
this is my object:
const formData = {
location: location,
cost: cost,
email: email,
image: image,
};
This is my fetch post method :
fetch("http://localhost:5000/places", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(formData),
})
.then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
I can see the image file object in client site console but I am not getting that in expreess server.
You have to send your input data as FormData to share images/files to the backend.
function uploadImage() {
let formData = new FormData(yourFormData);
fetch("http://localhost:5000/places", {
method: "POST",
body: formData,
}).then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
}
uploadPictures = (event) => {
let formData = new FormData();
let image = event.target.files[0];
let color = [0,153,255];
formData.append('image', image);
formData.append('color', color);
let url = FormatUrl(`/store_image?`, true)
fetch(url, {
method: 'post',
headers: {
"Content-Type": "multipart/form-data",
"Accept": '*/*',
"type": "formData",
},
body:formData,
})
.then(response => response.json())
.then(res => {
this.setState({
imgSrc: res.image_url
})
}).catch(err => {
console.log(err)
})
}
Here i am trying to upload image to backend using above function.
But it is not working. while it is working fine for postman.
I think something is wrong with my headers
Please have a look
how to upload image to api using axios
i want to upload image with data to api using axios
i try with formdata but it did not work see below my code
and this is my code
uploadToServer= () => {
const file =this.state.photo
let formdata = new FormData()
formdata.append('sale_id', 1)
formdata.append('note_type_id', 4)
formdata.append('description', "test")
formdata.append('note_content_item', "test")
formdata.append('Note', file)
axios.post('api',
{data:formdata},{headers: {
'Content-Type' : 'multipart/form-data',
'Authorization':'xx'
}
})
.then(resp => console.log(resp))
.catch(error => console.error(error));
}
i try a lot of solution but it give me
Error: Request failed with status code 500
The 500 Internal Server Error is a very general HTTP status code that means something has gone wrong on the server.
You can request like this (using fetch):
let formdata = new FormData()
formdata.append('description', "test")
let i = {
uri: image.path,
type: 'multipart/form-data',
name: `image.jpg`,
};
formdata.append('image', i);
fetch(YourApi,{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then(response => {
response.text().then((res)=>{
console.warn(res)
})
}).catch(err => {
console.warn('error')
})
so i want to upload
object as data
and file as Note
to api using axios
uploadToServer= () => {
const file =this.state.photo
let data2 ={sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
let data = new FormData()
data.append('data[sale_id]', '1')
data.append('data[note_type_id]', '4')
data.append('data[description]', "test")
data.append('data[note_content_item]', "test")
console.log(data)
axios({
url: api',
method: 'POST',
data: data,
headers: {
'Content-Type' : 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(resp => console.log(resp.data.response))
.catch(error => console.error(error));
}
first i am trying with data without Note i can do it in postman
but with my code i got error
message: "Can not save file"
response_code: 10
i got this error only if i change the key from data to something else
when you are using react-native you don't need "form-data" package. Because react native polyfills standard FormData api and exports it as global.
second problem is axios converts form data automatically to string, so you need to use transformRequest config on request to override it.
import { AxiosRequestConfig } from "axios";
const FormData = global.FormData;
const axiosInstance = axios.create({
baseURL: 'example.com', // use with scheme
timeout: 30000,
headers: {
"X-Platform": 'iOS',
"X-App-Build-Number": '1.0.0',
},
});
const formData = new FormData();
formData.append("userId", "123456");
formData.append("file", {
uri: "/dev/sda/abc.png",
type: "image/png",
name: "abc.png",
});
const config: AxiosRequestConfig = {
method: "post",
url: "/process/start",
responseType: "json",
headers: {
'Content-Type': 'multipart/form-data',
// if backend supports u can use gzip request encoding
// "Content-Encoding": "gzip",
},
transformRequest: (data, headers) => {
// !!! override data to return formData
// since axios converts that to string
return formData;
},
onUploadProgress: (progressEvent) => {
// use upload data, since it's an upload progress
// iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902}
},
data: formData,
};
// send post request and get response
const response = await axiosInstance.request(config);
You are not building FormData correctly, Try this:
let data = {sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
const formData = new FormData();
formData.append('data', JSON.stringify(data));
formData.append('Note', {
uri: "file://" //Your Image File Path
type: 'image/jpeg',
name: "imagename.jpg",
});
axios({
url : api,
method : 'POST',
data : formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(function (response) {
console.log("response :", response);
})
.catch(function (error) {
console.log("error from image :");
})
This might help you:
import {Platform} from 'react-native';
import axios from 'axios';
const upload = async readPath => {
console.log('path', readPath);
const URL = 'your-url';
const headers = {
headers: {
'Content-Type': 'multipart/form-data',
Accept: 'application/json',
Authorization: `Bearer ${projectSecret}`,
},
};
const formData = new FormData();
const file = {
uri:
Platform.OS === 'android' ? `file:///${readPath}` : readPath,
type: 'text/plain',
name: name,
};
formData.append('file', file);
await axios
.post(URL, formData, headers, {
timeout: 3000,
})
.then(async response => {
console.log(response.data);
})
.catch(error => {
console.log('error : ', error);
});
};