reactjsaxiosrelative-addressing

using relative addressing for API inside Axios request


I'm working on an application where the URL/path to the API's CRUD functions are defined like so:

var newApiAddresses = {
        itemsGet: "<?php echo $view['router']->url('itembook_test_api_v1_apiitems_getitems'); ?>",
        itemAdd: "<?php echo $view['router']->url('itembook_test_api_v1_apiitems_itemadd'); ?>",
        itemEdit: "<?php echo $view['router']->path('itembook_test_api_v1_apiitems_itemedit', array('id' => null)); ?>",
        itemDelete: "<?php echo $view['router']->path('itembook_test_api_v1_apiitems_itemdelete', array('id' => null)); ?>"
    }

As expected the path for edit and delete receive an id. Now in my application I can create a post and get request with the urls defined in this manner like so:

  handlePostItemToApi () {
    axios.post(newApiAddresses.itemAdd, {
      "itemId": 1,
      "date": this.changeDateFormat(),
      ...

The above sends the POST request with no problem. But when I need to edit an item, I need to somehow include the itemid into this url. I tried doing it like so but it did not work

  handleEditItemToApi () {
    axios.put(newApiAddresses.itemEdit/{$id}, {
      "itemId": 1,
      "date": this.changeDateFormat(),
      ...

What is the correct way to include the id in the above url for put. I cannot hardcode the url like e.g. 'http://localhost/app_dev.php/api/v1/items/{$id}' as shown in axios documentation


Solution

  • You can do it using the back quotes(not the usual single quote) in following way,

     axios.put(`newApiAddresses.itemEdit/{$id}`, {
    

    or using the single quote as,

    axios.put('newApiAddresses.itemEdit/'+id, {