是否可以为提取构建一个通用函数?
Is it possible to build a generic function for the fetches?
我在 react.js 中构建了一个包含大量 'crud' 操作的应用程序。我是 React 的初学者。对于所有这些提取,总是有相同的 header (content-type, token...)。对于每个请求,我必须解决承诺、测试代码状态、解析答案、管理错误等......写起来很长。
所以我想知道是否可以构建一个通用函数。类似的东西:
myBooks = callApi('endpoint', 'myparams');
仅此而已!函数 callApi 将执行所有必要的操作(添加 headers、令牌等....)。
我在我这边尝试过,但我没有足够的技能在 React 中做到这一点。
您是否使用特殊包装进行提取?或者你像我一样写你的抓取,太糟糕了,写起来太长了。
你有什么套餐可以推荐吗?
我正在使用 axios
从 REST api 中获取数据。您可以使用 axios.create
创建一个实例,您可以传递 headers 和 API 的基数 url。您甚至可以使用 axios 定义中间件。
使用axios create:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
就个人而言,我更喜欢像这样包装我的 axios 调用:
function getHeaders() {
return {
accept: 'application/json',
authorization: `Bearer ${ getStoredAuthToken() }`,
};
}
function postHeaders() {
return {
'content-type': 'application/json',
authorization: `Bearer ${ getStoredAuthToken() }`,
};
}
export const postRequest = ( endpoint, data ) => axios
.post( API + endpoint, data, { headers: postHeaders() } )
.then( res => res.data )
.catch( ( err ) => {
LoggingUtility.error( `Error in post request to entpoint ${ endpoint }`, err );
if ( isNetworkError( err ) ) {
throwServerNotReachableError();
}
const { status } = err.response;
if ( isUnauthorizedError( status ) ) {
return refreshAuthToken(
() => postRequest( endpoint, data ),
);
}
throw err;
} );
您可以对每个 http 方法执行类似的操作,例如deleteRequest、putRequest、postRequest 等
在 React/Frontend 土地上,在名为 services
的文件夹中执行此操作非常常见,该文件夹抽象出所有异步数据提取。
我以前在个人项目上确实这样做过,这是我使用的基础知识。
const baseUrl = 'http://localhost';
const port = '8080';
export async function get(route) {
try {
const response = await fetch(`${baseUrl}:${port}/${route}`, {
method: 'GET',
cache: 'no-cache',
credentials: 'same-origin',
});
return response.json();
} catch (err) {
console.error(`GET error: ${err}`);
}
}
当然,您必须修改它以进行身份验证、https 等,但您可以使用类似的方式调用它(对于类似的 post 方法)(还有一个用于获取):
const response = await post('user-files/update', {
uuid,
newFilename: filename,
originalFilename,
});
const rows = await get(`dataset/${uuid}`);
完全是。您可以像这样创建一个 callApi 函数:
const callApi = (url, params) => {
let token = localStorage.getItem('token');
let heads = {};
let body = params;
if (token !== null && token !== undefined && token !== ''){
heads['token'] = token;
}
heads["Content-Type"] = "application/json";
body = params && JSON.stringify(params);
let options = {
mode: "cors",
method: "POST",
headers: heads
};
if (body) options['body'] = body;
try {
const response = await fetch(url, options);
const res = await response.json();
return res;
} catch (error) {
console.log(error);
}
}
希望对您有所帮助!!
我在 react.js 中构建了一个包含大量 'crud' 操作的应用程序。我是 React 的初学者。对于所有这些提取,总是有相同的 header (content-type, token...)。对于每个请求,我必须解决承诺、测试代码状态、解析答案、管理错误等......写起来很长。
所以我想知道是否可以构建一个通用函数。类似的东西:
myBooks = callApi('endpoint', 'myparams');
仅此而已!函数 callApi 将执行所有必要的操作(添加 headers、令牌等....)。
我在我这边尝试过,但我没有足够的技能在 React 中做到这一点。
您是否使用特殊包装进行提取?或者你像我一样写你的抓取,太糟糕了,写起来太长了。
你有什么套餐可以推荐吗?
我正在使用 axios
从 REST api 中获取数据。您可以使用 axios.create
创建一个实例,您可以传递 headers 和 API 的基数 url。您甚至可以使用 axios 定义中间件。
使用axios create:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
就个人而言,我更喜欢像这样包装我的 axios 调用:
function getHeaders() {
return {
accept: 'application/json',
authorization: `Bearer ${ getStoredAuthToken() }`,
};
}
function postHeaders() {
return {
'content-type': 'application/json',
authorization: `Bearer ${ getStoredAuthToken() }`,
};
}
export const postRequest = ( endpoint, data ) => axios
.post( API + endpoint, data, { headers: postHeaders() } )
.then( res => res.data )
.catch( ( err ) => {
LoggingUtility.error( `Error in post request to entpoint ${ endpoint }`, err );
if ( isNetworkError( err ) ) {
throwServerNotReachableError();
}
const { status } = err.response;
if ( isUnauthorizedError( status ) ) {
return refreshAuthToken(
() => postRequest( endpoint, data ),
);
}
throw err;
} );
您可以对每个 http 方法执行类似的操作,例如deleteRequest、putRequest、postRequest 等
在 React/Frontend 土地上,在名为 services
的文件夹中执行此操作非常常见,该文件夹抽象出所有异步数据提取。
我以前在个人项目上确实这样做过,这是我使用的基础知识。
const baseUrl = 'http://localhost';
const port = '8080';
export async function get(route) {
try {
const response = await fetch(`${baseUrl}:${port}/${route}`, {
method: 'GET',
cache: 'no-cache',
credentials: 'same-origin',
});
return response.json();
} catch (err) {
console.error(`GET error: ${err}`);
}
}
当然,您必须修改它以进行身份验证、https 等,但您可以使用类似的方式调用它(对于类似的 post 方法)(还有一个用于获取):
const response = await post('user-files/update', {
uuid,
newFilename: filename,
originalFilename,
});
const rows = await get(`dataset/${uuid}`);
完全是。您可以像这样创建一个 callApi 函数:
const callApi = (url, params) => {
let token = localStorage.getItem('token');
let heads = {};
let body = params;
if (token !== null && token !== undefined && token !== ''){
heads['token'] = token;
}
heads["Content-Type"] = "application/json";
body = params && JSON.stringify(params);
let options = {
mode: "cors",
method: "POST",
headers: heads
};
if (body) options['body'] = body;
try {
const response = await fetch(url, options);
const res = await response.json();
return res;
} catch (error) {
console.log(error);
}
}
希望对您有所帮助!!