send file from formik reactjs to springboot using axios with saga - reactjs

i can send file "userPicture" from postman and get it in the backend (springboot )and i save it to my database mongodb without any problem
but when i send the picture from the form i use Formik component in reactjs and axios
i display the content of my input userPicture i get
in axios i made this to sent the request. for boundary i dont know what is i made copy past "WebKitFormBoundaryQ0pBuvRC1EzDAQWT" from an exemple
try {
const { user } = action;
console.log(user);
const request = yield axios({
method: 'post',
url: ENDPOINTS.USER + '/add',
data: user,
headers: { 'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundaryQ0pBuvRC1EzDAQWT----' }
});
in the backend i get this error
,org.springframework.validation.BindingResult,org.springframework.web.multipart.MultipartFile,org.springframework.web.multipart.MultipartFile)
throws java.io.IOException: Required request part
'userPicture' is not present
i get the same error in postman when i send request without userPicture parameter

Looks like you sending the file incorrectly. If you want to send multipart/form-data from client to server, you need to use FormData.
Like this
const formData = new FormData();
formData.append('usePicture', user)

Related

Axios POST request

I am trying to send some data from a form to a database using Axios. Here is the code:
const handleSubmit = async () => {
try {
const response = await axios.post(
ApiUrl,
{
batchId,
name,
description,
source,
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
console.log(response.data);
handleModal();
} catch (error) {
console.error(error.response.data);
}
};
The error I get is this:
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
The values are being stored with useState. The database is receiving inputs but with no data.
I was investigating and I think I need to convert the JSON data to string, but I am not sure how to do that for my code.
If the database is receiving inputs but with no data, it sounds like the API endpoint is being hit properly but you are either improperly extracting the data from (Express?) or improperly passing the extracted values through to whatever function stores them in the database.
You do not need to stringify your axios.post payload.
If you're using Express, make sure you're properly extracting the data from req.body in your endpoint handler. If you're using req.params or req.query that would be a problem.
I would set up some console.log('###') markers in your backend code to ensure the data is reaching the query insertion point.
If you are still having issues, please provide more context regarding your backend logic and the trail between your API and the Database.
I hope this helps!

Django server unable to get data from react Axios

I'm not getting an error but when I saw the logs of my server it prints an empty object {} whenever I send a request to the sever from my react app using axios. I double checked everything every other request in another components of my app works fine, but only in this particular request the data is not being sent! I have no CORS issue!
My react axios request
// PrivateAxios instance to send api request
const axiosPrivate = useAxiosPrivate();
const handleSearch = async () => {
const data = JSON.stringify({ from_company: keyWord });
try {
const response = await axiosPrivate.get(SEARCH_URL, data);
console.log(response);
setRecords(response?.data);
} catch (err) {
if (!err?.response) {
console.log("NO SERVER RESPONSE");
} else {
console.log("SOMETHING WRONG");
}
}
};
Server log
{} <-- Prints the request.data as an empty object
"GET /api/find_many/ HTTP/1.1" 200 6276
The django server responses with correct details when I send a request with Postman or Thunder Client. The server also prints the object that were sent with the Postman request. I don't know why the server is unable to get the object or data when I request from my react app.
Request sent from Postman returns
{'from_company': 'Jethmal Paliwal'} <-- Prints the request.data correctly
"GET /api/find_many/ HTTP/1.1" 200 2284
I have double checked everything, my headers are set correctly, Content-Type: application/json, withCredentials: true, and every other possible settings, Even every request from other components works great, but why this particular request doesn't reach the server?
Tried writing the data as an Object in the request funcion itself
const response = axiosPrivate.get(SEARCH_URL, { "from_company": "Jethmal Paliwal" }); which doesn't work as well. The same empty object gets printed.
Tried JSON.stringify the data, which doesn't work as well.
I believe that axios is omitting the data as it's not per REST standard to submit data in the GET request. HTTP allows that, but people and apparently libraries are not expecting it.
This is the API for axios get method:
axios.get(url[, config])
as you see there is no data in the method signature. And if we look at the POST method:
axios.post(url[, data[, config]])
I suggest if you have data to submit to server that you use a POST method instead.

Not getting data with codeingiter api hitting with react js browser build fetch method

I have created an API with Codeigniter , i test it with postman it is working fine there but when I am hitting it with react js the post data is not appearing on the server side
here is the react code
async function submitForm() {
const response = await fetch(
"url",
{
method: "POST", // *GET, POST, PUT, DELETE, etc.
body: JSON.stringify({
first_name: enteredFirstName,
last_name: enteredLastName,
email: enteredEmail,
company_name: enteredComapanyName,
phone: enteredPhone,
company_type: cType,
}), // body data type must match "Content-Type" header
}
);
console.log(response.json());
}
here is the server-side Codeigniter code
header("Access-Control-Allow-Origin: *");
print_r($_POST);
I am passing value from the client side but not getting it on the server side
I am getting an empty array
I am expecting an array of data I am passing from the client side
I tried almost all the headers but not getting any data
I think it might be a header issue because i am getting data in the firebase
The problem is that I am passing data with JSON and getting the data on the server side is form data that's why it was an empty array
this is how i get the json data
$data = json_decode(file_get_contents('php://input'), true);

Post Request from axios always returns Unauthorized despite having valid JWT set in header/Axios Deletes Headers

I set up passport-local to login a user, and then once logged in, the user will be given a JWT token through passport-JWT. The JWTStrategy is set up to use
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken() so that the JWT can sent with the Authorization header Authorization: `Token ${userContext.token}`}. In my react client side, I have set up a GET request using axios as shown here:
const fetchProfileDetails = async(config)=>{
const res = await axios.get("http://localhost:8080/users/me", config)
}
const config = {
method:"GET",
withCredentials: true,
headers: {Authorization: `Bearer ${userContext.token}`}
}
This request successfully authenticates and returns the user data from /me.
Now heres the kicker: when I use the exact same request structure, but switch the method to post in the axios request and in my express route in the backend, the request always responds with a 401 Unauthorized.
However, when I send the same request from POSTMAN, with the same Bearer Token used in the request that was Unauthorized, the request succeeds without any errors.
TLDR: GET requests work with the JWT token and return with a 200 status code, while the same request with a POST method returns with a 401 status code.
What am I missing here??!
You are probably using there GET and not using POST anywhere.
In your code, you have code only for get. You will need to write code for post as well.
Below is the code for post for your reference:
router.post('/', config, async(req, res, next) => {
const { error } = validateBody(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
const newData= new passport({ name: req.body.name });
await newData.save();
console.log('saving the document');
res.send(newData);
})
Your code should have post as well. Writing single code will not work. You need to have to write code for every condition and every possibility. So like for get need code for post as well, also if you have condition for patch or delete or put you will have to write the axios method for that as well.
Hope this has helped you in any way.
I have come upon a solution for this issue. For some reason, axios was not maintaining the Authorization header I had set in my config variable, and deleted it upon making the request. To solve this, I just had to reshuffle my axios request to look like this:
const res = await axios({
method:'POST',
url:"http://localhost:8080/users/test",
headers:{'Authorization':`Bearer${token}`
}})
I feel cheated as I spent a ton of time on this and the solution was so underwhelming. Axios was trolling me the whole time :/

Upload csv file in Reatjs frontend and send it back to backend server

I want to upload csv file in Reatjs frontend and send it back to the backend server(Spring Rest API).
NPM has lot of things that solve this issue. Checkout react-upload-file
you could simply make a post http request with the file appended in a form data object, like this using axios (or any other lib you prefer)
const formData = new FormData();
formData.append("file", yourStateFile);
axios.post('yourUrl', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

Resources