send data, url, and method to axios as arguments - reactjs

I am trying to make custom request with axios and pass the method, url and body as arguments like that
const response = await axios({ url, body, method });
but the body doesnot reach to the backend. what is the right way to send data like that?

The config property you're searching for is called data not body. Rename your variable to data and pass it or don't use the object shorthand operator and rename it to data. Like this:
const response = await axios({ url, data: body, method });
In the axios documentation is a list of all available properties.

Related

How to do a HTTP head request in next.js

I want to achieve the same done here but in next.js.
Next.js provides methods to fetch data from a server and using them as props. I don't know whether you want to use it before rendering a page (like getServerSideProps) or when, for example, you click a button, but I suppose its the first case.
My personal preference when doing requests, is axios, so I will use it in this example:
export async function getServerSideProps({ req, res }) {
// Here is where we make the request
const result = await axios({
method: 'HEAD', // here is where we declare that we want to use the HEAD method
url: "your server url", // this is the url where we want to send the request
headers: {} // if you want to add custom headers, you can do it here
})
// Here we are logging the result of the request
console.log(result)
}
You can refer to the next.js documentation on data fetching and the axios documentation
Have a great day and I hope you succeed on your projects

Axios multipart request by PUT method

I want to make a put multipart request but it is calling POST even though I tried setting the method to "PUT"
config = {..., method:"PUT"}
axios.request("/getAll", formData, config)
Also, I have a confusion regarding two methods of Axios
Axios.request() and Axios.get()
What is the difference when we call request with method set to GET in config while calling axios.request() and directly calling axios.get()?
Thanks in advance
axios.request takes only 1 argument: config. So you should use:
axios.request({ url: '/getAll', method: 'put', data: formData })
axios.get, axios.put etc are aliases for requests, so you just write less code, because you don't need to specify request's type
axios.put('/getAll', formData)
As a summary, there is no difference between:
axios.request({ url: '/getAll', method: 'get' })
and
axios.get('/getAll')
The second option is just easier and cleaner.

Axios in React app. Posting image with form data sends request with empty body

I'm trying to send image file to my backend API. Last works fine with Postman. The problem is not with image, I'm not able to send any request with axios and form data, no meter I append image or not.
Everything works fine with fetch. It took time to understand, that fetch does not need any content type, and last generates automatically as multipart/form-data with right boundary.
As written axios should do same as fetch, but it does not generate or change its content-type. Passing header 'content-type' : 'multipart/form-data does not do the trick of course. When I do not set content type it just use application/json. I was not able to find anything like that in documentation. Everywhere its says, that axios should create content type header automatically.
My axios version is 0.18.0.
Here is code, it can't be more simple =)
axios
.post(url, payload)
#######UPDATE#######
It turned out the problem was with axios interceptor. If you don't use interceptors you won't get this problem. So when I created new instance and deleted all headers no interceptors where called that's why my code worked. But let me bring more details to help others avoid this pain. Interceptor has transformRequest function where this part of code exists
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
where setContentTypeIfUnset function is
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
So if your object has undefined headers you will also pass this situation. But in my case even after deleting all headers I must pass some header to my application. And on setting it interceptor calls that transfromRequest function which adds that header to my formdata request.
I hope in future releases axios will fix this issue.
#######OLD ANSWER#######
As I guessed, somehow axios in my project set its default value for header content type and even setting it as 'content-type' : undefined did not overwrite that value.
Here is solution
let axiosInstance = axios.create();
delete axiosInstance.defaults.headers;
Then use that instance.
Spent whole day to find this solution.
const formData = new FormData();
formData.append('image', image); // your image file
formData.append('description','this is optional description');
Axios.post(`your url`, {body:formData}, {
headers: {
'content-type': 'multipart/form-data'
}
})
Can you please try this code once ?
You can try like this:
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

send file from formik reactjs to springboot using axios with saga

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)

Using Fetch API with cross-fetch polyfill to upload file on file-input change

I'm using the Fetch API with the cross-fetch polyfill https://www.npmjs.com/package/cross-fetch
Been farting around on SO for several hours trying to get file upload working using it. No matter what I do, I can't seem to avoid the 'unsupported BodyInit type' error.
<input
name="file"
type="file"
onChange={event => {
event.preventDefault();
var f = event.target.files[0];
var data = new FormData();
data.append("file", f);
fetch("/my-api", {
method: "POST",
body: data
});
}}
/>
Here's a runnable example: https://codesandbox.io/s/v08lpj24wy
Of course, I wouldn't do this sort of thing inside an onChange handler directly, but the example illustrates the error. What am I doing wrong?
Turns out your import fetch from "cross-fetch" is shimming fetch incorrectly, by breaking the parsing of blobs and FormData. Just remove the import and see that everything works.
fetch returns a promise. It doesn't do anything until you call then
edit
If you call fetch with a Request object the error dissapears
var req = new Request("/my-api", {
method: "POST",
body: data
});
fetch(req)
.then(() => console.log("ok"))
.catch(() => console.error("not ok"));
Actually that's an issue with github's fetch that cross-fetch uses to fetch on the browser environment. http://github.com/github/fetch/issues/601
You can't pass a file directly as body. You must take the 2nd approach
by wrapping it in a FormData. When passing a FormData to body, you
must not set any Content-Type header for the request. Instead, the
browser will choose the appropriate multipart/form-data value.

Resources