我将Axios与NodeJs结合使用,并尝试在axios.get()方法中传递路径参数。例如,如果URL是url = '/fetch/{date}',我想{date}在调用时用实际日期替换axios.get(url)。
我遍历了Github和StackOverflow上的源代码,但是找不到任何方法。
是否可以保留带有参数的URL作为占位符并在实际调用Axios的get方法时替换它们?
thi*_*113 12
我认为使用 axios 拦截器可以更好地做到这一点:
//create your instance
const instanceAxios = axios.create({
baseUrl: 'http://localhost:3001'
]);
instanceAxios.interceptors.request.use(config => {
if (!config.url) {
return config;
}
const currentUrl = new URL(config.url, config.baseURL);
// parse pathName to implement variables
Object.entries(config.urlParams || {}).forEach(([
k,
v,
]) => {
currentUrl.pathname = currentUrl.pathname.replace(`:${k}`, encodeURIComponent(v));
});
const authPart = currentUrl.username && currentUrl.password ? `${currentUrl.username}:${currentUrl.password}` : '';
return {
...config,
baseURL: `${currentUrl.protocol}//${authPart}${currentUrl.host}`,
url: currentUrl.pathname,
};
});
// use like :
instanceAxios.get('/issues/:uuid', {
urlParams : {
uuid: '123456789'
}
})
Run Code Online (Sandbox Code Playgroud)
对于打字稿用户,您需要将其添加到您的 .d.ts 之一中
declare module 'axios' {
interface AxiosRequestConfig {
urlParams?: Record<string, string>;
}
}
Run Code Online (Sandbox Code Playgroud)
(这是一个 POC,未经真正测试,如果您发现有问题,请不要犹豫)
使用模板字符串
url = `/fetch/${date}`
Run Code Online (Sandbox Code Playgroud)
或者只是标记它
url = '/fetch/'+ date
Run Code Online (Sandbox Code Playgroud)
Axios 没有这个功能,看起来团队不想添加它。
感谢以前的响应者的灵感,对我来说,这似乎是最接近您(和我)正在寻找的解决方案:
1 - 要存储所有 URL 及其参数的位置,将它们定义为使用模板字符串返回组合 URL 的函数:
export var fetchDateUrl = (date) => `/fetch/${date}`;
Run Code Online (Sandbox Code Playgroud)
如果您需要对连接到 URL 中的值进行任何特定于类型的格式化,这个函数是一个很好的地方。
2 - 在您要发出请求的地方,使用正确的参数调用函数:
import { fetchDateUrl } from 'my-urls';
axios.get(fetchDateUrl(someDateVariable))...;
Run Code Online (Sandbox Code Playgroud)
另一种变体,如果您真的喜欢在调用站点命名参数的想法,您可以定义 URL 函数来解构这样的对象:
var fetchDateUrl = ({date}) => `/fetch/${date}`;
Run Code Online (Sandbox Code Playgroud)
然后你会像这样使用它:
axios.get(fetchDateUrl({date: someDateVariable}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8696 次 |
| 最近记录: |