mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-10-29 18:14:34 +08:00
refactor: replace axios with fetch (#41944)
This commit is contained in:
+26
-17
@@ -1,41 +1,52 @@
|
||||
import envData from '../../../config/env.json';
|
||||
import axios from 'axios';
|
||||
import Tokens from 'csrf';
|
||||
import cookies from 'browser-cookies';
|
||||
|
||||
const { apiLocation } = envData;
|
||||
const { apiLocation, environment } = envData;
|
||||
|
||||
const base = apiLocation;
|
||||
const tokens = new Tokens();
|
||||
|
||||
axios.defaults.withCredentials = true;
|
||||
// TODO: test on staging. Do we need 'include' everywhere?
|
||||
const defaultOptions = {
|
||||
credentials: environment === 'development' ? 'include' : 'same-site'
|
||||
};
|
||||
|
||||
// _csrf is passed to the client as a cookie. Tokens are sent back to the server
|
||||
// via headers:
|
||||
function setCSRFTokens() {
|
||||
function getCSRFToken() {
|
||||
const _csrf = typeof window !== 'undefined' && cookies.get('_csrf');
|
||||
if (!_csrf) return;
|
||||
axios.defaults.headers.post['CSRF-Token'] = tokens.create(_csrf);
|
||||
axios.defaults.headers.put['CSRF-Token'] = tokens.create(_csrf);
|
||||
if (!_csrf) {
|
||||
return '';
|
||||
} else {
|
||||
return tokens.create(_csrf);
|
||||
}
|
||||
}
|
||||
|
||||
function get(path) {
|
||||
return axios.get(`${base}${path}`);
|
||||
return fetch(`${base}${path}`, defaultOptions).then(res => res.json());
|
||||
}
|
||||
|
||||
export function post(path, body) {
|
||||
setCSRFTokens();
|
||||
return axios.post(`${base}${path}`, body);
|
||||
return request('POST', path, body);
|
||||
}
|
||||
|
||||
function put(path, body) {
|
||||
setCSRFTokens();
|
||||
return axios.put(`${base}${path}`, body);
|
||||
return request('PUT', path, body);
|
||||
}
|
||||
|
||||
// function del(path) {
|
||||
// return axios.delete(`${base}${path}`);
|
||||
// }
|
||||
function request(method, path, body) {
|
||||
const options = {
|
||||
...defaultOptions,
|
||||
method,
|
||||
headers: {
|
||||
'CSRF-Token': getCSRFToken(),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
};
|
||||
return fetch(`${base}${path}`, options).then(res => res.json());
|
||||
}
|
||||
|
||||
/** GET **/
|
||||
|
||||
@@ -106,5 +117,3 @@ export function putUserUpdateEmail(email) {
|
||||
export function putVerifyCert(certSlug) {
|
||||
return put('/certificate/verify', { certSlug });
|
||||
}
|
||||
|
||||
/** DELETE **/
|
||||
|
||||
Reference in New Issue
Block a user