使用axios配置驼峰式案例分析器

If you work on a project in which the frontend and backend are developed in different languages, there is a high probability that you will have values with different naming conventions traveling through HTTP requests.

如果您在一个项目中使用不同的语言开发前端和后端,那么很有可能您将拥有通过HTTP请求传递不同命名约定的值。

In this short article I will show you a strategy so that you can maintain the naming convention of the values according to the programming language you are using and thus maintain a standardised code style in your applications.

在这篇简短的文章中,我将向您展示一种策略,以便您可以根据所使用的编程语言来维护值的命名约定,从而在应用程序中维护标准化的代码风格。

在前端配置解析器 (Configuring the parser on the Frontend)

First of all, you need to install axios and a library called humps in your project:

首先,您需要安装爱可信和一个叫库在你的项目中:

yarn add axios humps @types/humps

That done, you can configure the axios interceptors as follows:

完成后,您可以按如下方式配置axios拦截器:

import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';import { camelizeKeys, decamelizeKeys } from 'humps';const api = axios.create({ baseURL: 'localhost:3000' });// Axios middleware to convert all api responses to camelCase
api.interceptors.response.use((response: AxiosResponse) => {
if (
response.data &&
response.headers['content-type'] === 'application/json'
) {
response.data = camelizeKeys(response.data);
} return response;
});// Axios middleware to convert all api requests to snake_case
api.interceptors.request.use((config: AxiosRequestConfig) => {
const newConfig = { ...config };
newConfig.url = `api/${config.url}`; if (newConfig.headers['Content-Type'] === 'multipart/form-data')
return newConfig; if (config.params) {
newConfig.params = decamelizeKeys(config.params);
} if (config.data) {
newConfig.data = decamelizeKeys(config.data);
} return newConfig;
});export default api;

Note that in the code above, some validations are made to check whether the intercepted call should be converted or not. You can add as many validations as you need.

请注意,在上面的代码中,进行了一些验证以检查是否应转换被拦截的调用。 您可以根据需要添加任意数量的验证。

With the little code above, you have a parser that manages to maintain the style pattern in the frontend and backend of your applications.

有了上面的小代码,您就有了一个解析器,该解析器设法在应用程序的前端和后端维护样式模式。

It is also worth mentioning that humps also has functions to convert PascalCase values 😎.

还值得一提的是,驼峰还具有转换PascalCase值functions的功能。

I hope this small tutorial can help you with your projects! Thanks for reading!

我希望这个小教程可以对您的项目有所帮助! 谢谢阅读!

翻译自: https://medium.com/javascript-in-plain-english/configuring-a-camelcase-to-snake-case-parser-with-axios-9fa34fd3b16f

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值