Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created April 8, 2020 14:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcoles/a1e8725a7dc2dfc41536251a99851b44 to your computer and use it in GitHub Desktop.
Save mrcoles/a1e8725a7dc2dfc41536251a99851b44 to your computer and use it in GitHub Desktop.
An example of making an AxiosRequestConfig object to do a multipart/form-data request
import axios, {
AxiosRequestConfig,
Method,
} from 'axios';
export const makeAxiosRequestConfig = (
method: Method,
path: string,
data?: { [key: string]: any },
params?: any
): AxiosRequestConfig => {
let headers: AxiosRequestConfig['headers'] = {};
let formData: FormData | undefined = undefined;
if (data) {
headers['Content-Type'] = 'multipart/form-data';
formData = new FormData();
Object.entries(data).forEach(([key, val]) => {
// HACK - make type happy…
const hackVal = val as string | File;
formData.append(key, hackVal);
});
}
return {
method,
url: `${ENDPOINT}${path}`,
data: formData,
params,
headers,
};
};
@mrcoles
Copy link
Author

mrcoles commented Apr 8, 2020

This handles both regular and form data, so you can send files to your server. You would use it like…

const cfg = makeAxiosRequestConfig('PATCH', '/api/foo', myFormData);
cons resp = await axios(cfg);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment