Axios doenst send formData in put method - reactjs

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" },
})ยด

Related

How to send React Native Camera captured image to Back-end Laravel?

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.

Axios: Pass data in GET method

I have created a config file to create an Axios.
export const http = axios.create({
baseURL: process.env.REACT_APP_API_URI,
responseType: "json",
timeout: 30000,
timeoutErrorMessage: "Request Time out",
headers: {
withCredentials:true
}
})
In the other file, I have created helper functions to post, update, and get. Now I am trying to pass data from the body through the get function so far I have following code to get data without passing the body.
export const getRequest = (url, is_strict = false) => {
return new Promise((resolve, reject) => {
http.get(url, {
headers: getHeaders(is_strict)
}).then((response) => {
if(response.status === StatusCodes.OK || response.status === StatusCodes.CREATED){
resolve(response.data);
} else {
reject(response);
}
})
.catch((error) => {
reject(error);
})
})
}
How can I achieve that?
You cannot have a request body in GET method. You can use request params instead. Or you can use POST method.
Form the MDN docs for GET,
property
avaiability
Request has body
No
Request has body
Yes

Axios delete not working , It is showing pending status in network tab in chorme

I'm using axios Delete method to delete my record. When I'm sending request , it is not returning any response. I was seen in networktab in chrome, there the API status is pending state. I'm using Redux and React. Below is my code
I'm importing service.js file in Action.js
Action.js file
const delete = formData => {
return async dispatch => {
const data = deleteservice.deleteRetail(formData)
.then({
console.log(response)
}).catch(error => {
console.log(error);
})
}
}
service.js
export const deleteRetail = (formData) => {
return axios({
method: 'DELETE,
URL : myURL,
headers: {
'content-type' : 'application/json'
},
data : {
userID: 'test',
userName : 'test'
}
})
}
This is my code, While I'm calling this delete url , status showing as pending in network. not getting any response.
Please suggest me the solution

Body of request received on Express backend is different than how i sent it from React frontend

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

File upload using .fetch() in ReactJS

I am trying to upload file using .fetch() in ReactJS as Front End and Laravel as Back End. My ReactJS code is like below
update= (event) => {
let uploadImage = event.target.file;
let form = new FormData()
form.append('uploadImage',uploadImage)
fetch('http://127.0.0.1:8000/api/addresses/upload', {
headers: {
'Authorization': 'Bearer ' + Auth.getToken(),
'Content-Type': 'multipart/form-data',
},
method: "POST",
body: form,
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
My Laravel code is like below
public function fileUpload(StoreImageRequest $request)
{
$image = $request->uploadImage;
$imagename = time() . $image->getClientOriginalName();
$destinationPath = public_path('/images');
$uploadValue = $image->move($destinationPath, $imagename);
if ($uploadValue) {
return response()->json($imagename);
}
}
I am getting error like below
and
Where is the issue ?
It's because you upload the image with form field name avatar, but in your Laravel method you access it with uploadImage.
So you can try change it to the following:
$request->avatar
Please checkout the Laravel Files documentation and make sure you follow their best practices.
I had the same issue. I fixed it by removing the content type.
Please check this article
https://upmostly.com/tutorials/upload-a-file-from-a-react-component

Resources