I have captured an image with React Native (expo-app) and can't find a proper way to send it to backend, mostly 500 and 422 appears (422 at this example).
Here is how a image data looks
{"base64": null, "height": 820, "uri": "file:///var/mobile/Containers/Data/Application/792E2665-5063-4853-876E-3793568C7FCF/Library/Caches/ExponentExperienceData/%2540anonymous%252Fexpo-app-27783a0c-0a97-44a6-be26-48d37639bb25/ImageManipulator/9FCEF372-7C90-484F-9028-7D4271F9978D.jpg", "width": 476}
Here is the axios request to the backend, a photo state contains the data of image like above
const handleSubmit = async() => {
const formData = new FormData();
formData.append("photo", {
uri: photo.uri,
name: photo.uri.split('/').pop(),
type: 'image/jpg'
});
await axios.post("/api/upload", {
formData
}, {
headers: { "Content-Type": "multipart/form-data" },
}).then(response => {
console.log(response.data)
})
}
Here is the laravel side, it can't go through validation
public function store(Request $request)
{
$validated = $request->validate([
'photo' => 'required|mimes:jpg,png,jpeg'
]);
return response()->json([
'status' => 'successfuly executed',
]);
}
Here is the laravel err log of what was in the request, even though console logging in the front end right before sending request, an object of image exist.
{"formData": null}
I can't figure out how to upload or even get captured image to react back-end, any ideas?
await axios.post("/api/upload",
formData
, {
headers: { "Content-Type": "multipart/form-data" },
}).then(response => {
console.log(response.data)
})
remove brackets and try again
This image URI - file:///var/mobile/Containers/Data/Application/792E2665-5063-4853-876E-3793568C7FCF/Library/Caches/ExponentExperienceData/%2540anonymous%252Fexpo-app-27783a0c-0a97-44a6-be26-48d37639bb25/ImageManipulator/9FCEF372-7C90-484F-9028-7D4271F9978D.jpg is a reference to image data on device memory but not actually image data.
expo-image-picker returns base64 image data and you can upload them to your server.
Related
am trying to send a post request to a JSON server using react. I've captured the data from a form using react formik. When I try to make a post request, the server only creates an id but the rest of the data is not captured. I've tried logging out the data just before the fetch method and it appears. It's only the server that is not picking it.
Below is the submit method from formik.
const onSubmit = (values) => {
console.log(values)
fetch('http://127.0.0.1:8000/contacts/', {
method: 'POST',
body: JSON.stringify(values),
headers: {"Contect-Type": "application/json; charset=UTF-8"}
}).then(responce => {
if (!responce.ok) {
alert("Failed to add")
}else{
alert("Contact added")
}
return responce.json();
}).then(data => {
console.log('Added')
})
}
i'm trying to update a user's profile( social web app), i'm working with React as a frontend and laravel as a backend. the data includes an image, so i sent it using FormData, i'm doing a small validation in backend to check if data is sent to the backend, but i found that axios is not sending formData.
Here is my function that runs after submit:
const editProfile = (e) => {
e.preventDefault()
setLoading(true)
const formData = new FormData();
formData.append('avatar', pic.avatar)
formData.append('website', profile.website)
formData.append('addresse', profile.addresse)
formData.append('bio', profile.bio)
formData.append('phone', profile.phone)
formData.append('gender', profile.gender)
formData.append('full_name', auth.full_name)
formData.append('user_name', auth.user_name)
formData.append('email', auth.email)
console.log(formData)
axios.put(`api/profile/update/${id}`, formData).then((res) => {
if(res.data.success) {
console.log('success')
history.push(`/profile/${id}`)
}else {
console.log(res.data.message)
setLoading(false)
}
})
}
I only made gender is required in laravel:
public function update(Request $request, $id)
{
$profile = Profile::find($id);
if(is_null($profile)) {
return response()->json([
'success' => false,
'message' => 'Profile can not be found!'
]);
}else {
$validate = Validator::make($request->all(),[
'gender' => 'required'
]);
if($validate->fails()) {
return response()->json([
'success' => false,
'message' => $validate->messages()
]);
}else {...
As its mentioned in react logic, i'm doing console.log to check errors if the response is failed, and i;m getting gender field is required, i tried to do a console.log(profile.gender) before sending data to axios and i could see the value normaly,
So can anyone help me please?
I think you should change your header
for exapmple
.put(url, formData, {
headers: { "Content-type": "multipart/form-data" },
})
I solved the probleme,
Solution: i had to change method from put to Post (both in laravel route and react axios).
it works
let formData = new FormData();
formData.append("_method", "PUT");
formData.append("a", 1);
// add your variables
axios.post(url, formData, {
headers: { "Content-type": "multipart/form-data" },
})ยด
I am trying to use Camunda's REST api to deploy a new process. However, I keep getting this HTTP response when my function is called.
Response:
{"type":"InvalidRequestException","message":"No deployment resources contained in the form upload."}
My jsx function
async deployNewProcess(xmlData) {
const formData = new FormData()
const blob = new Blob([xmlData], {type:'application/octet-stream'})
formData.append('upload', blob)
const response = await fetch(`${baseurl}/deployment/create`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data; boundary=<calculated when request is sent>',
'Content-Length': '<calculated when request is sent>',
'Host': '<calculated when request is sent>'
},
body: formData
})
.then(result => console.log("SUCCESS: ", result))
.catch(err => console.log("ERROR: ", err))
}
Has anyone had any experience with this?
Based on this post https://camunda.com/blog/2018/02/custom-tasklist-examples/
see the example code
here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/middleware/api.js#L11
and here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/actions/camunda-rest/deployment.js#L4
I am trying to send a post request from my React front end to my Express front end, for some reason, the object I want to recieve, is being displayed so that the object is the key of another object and the value is and empty string.
Here is my onSubmit React function
handleSubmit = event => {
event.preventDefault()
const backend = '/api/login'
fetch(backend, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: JSON.stringify(this.state)
})
.then(res => {
res.json()
})
.then(user => {
console.log(user)
})
.catch(err => {
console.log(err)
})
}`
And my post function on the express server
app.post("/login", (req, res) => {
console.log(req.body)
})
For example, if the object I want to send is {username: "user1", password: "password"}, when I console.log(req.body), I get { '{"username":"user1","password":"password"}': '' } in the console.
How do i fix this so i get the object that I requested?
Because it is JSON format. To parse it you can use:
JSON.parse('{"username":"user1","password":"password"}')
or JSON.parse(req.body)
The approach is fine with JSON.stringify() because it should be posted just like a string to the server. But if you want it to be an object at the backend then you have to parse it back with:
const userObj = JSON.parse(req.body.Data); // it will parse it back as an object
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')
})