Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing path parameters in axios

Tags:

node.js

axios

I am using Axios with NodeJs and trying to pass path parameters in axios.get() method. For example, if URL is url = '/fetch/{date}', I want to replace {date} with the actual date while calling axios.get(url).

I went through the source code on Github and StackOverflow, but couldn't find any method.

Is it possible to keep URLs with parameters as a placeholder and replace them while actually calling the get method of Axios?

like image 350
Saheb Avatar asked Feb 12 '18 14:02

Saheb


People also ask

What are the parameters Axios method take?

Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server. For a simple Axios POST request, the object must have a url property. If no method is provided, GET will be used as the default value.

How do you send a body request in Axios?

Sending a PUT Request with Axios The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object: const res = await axios. put('/api/article/123', { title: 'Making PUT Requests with Axios', status: 'published' });

How do I get to Axios?

A GET request can be made with Axios to “get” data from a server. The HTTP get request is performed by calling axios. get() . The get() method requires two parameters to be supplied to it.


2 Answers

Axios doesn't have this feature and it looks like the team don't want to add it.

With credit to previous responders for inspiration, to me this seems like the solution closest to what you (and me) are looking for:

1 - Where you want to store all your URLs and their parameters, define them as functions which use a template string to return the composed URL:

export var fetchDateUrl = (date) => `/fetch/${date}`;

If you need any type-specific formatting of the value being concatenated into the URL, this function is a good place to do it.

2 - Where you want to make the request, call the function with the correct parameters:

import { fetchDateUrl } from 'my-urls';
axios.get(fetchDateUrl(someDateVariable))...;

Another variation, if you really like the idea of naming the parameters at the call site, you can define the URL function to destructure an object like this:

var fetchDateUrl = ({date}) => `/fetch/${date}`;

which you'd then use like this:

axios.get(fetchDateUrl({date: someDateVariable}));
like image 54
Graham Lea Avatar answered Oct 07 '22 17:10

Graham Lea


Use template strings

    url = `/fetch/${date}`

Or just tag it on

    url = '/fetch/'+ date
like image 6
sharkdawg Avatar answered Oct 07 '22 16:10

sharkdawg