Skip to content

Instantly share code, notes, and snippets.

@Ajith-Pandian
Created December 22, 2017 10:15
Show Gist options
  • Save Ajith-Pandian/7200f36b94bfcec4df7e2b86cbdee67b to your computer and use it in GitHub Desktop.
Save Ajith-Pandian/7200f36b94bfcec4df7e2b86cbdee67b to your computer and use it in GitHub Desktop.
Api with multipart formdata and token
export default class Api {
static headers() {
return {
Accept: "application/json",
"Content-Type": "multipart/form-data"
};
}
static get(route, token) {
return this.request(route, token, null, "GET");
}
static put(route, token, params) {
return this.request(route, token, params, "PUT");
}
static post(route, token, params) {
return this.request(route, token, params, "POST");
}
static delete(route, token, params) {
return this.request(route, token, params, "DELETE");
}
static request(route, token, params, verb) {
const host = "http://localhost:3000/";//SERVER BASE URL
const url = `${host}${route}`;
let formData = new FormData();
for (let name in params) {
formData.append(name, params[name]);
}
let options = Object.assign(
{ method: verb },
params ? { body: formData } : null
);
options.headers = { ...Api.headers(), token };
return fetch(url, options)
.then(response => response.json())
.then(responseJson => responseJson)
.catch(error => {
console.error(error);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment