adonis.jsadonisjs-ace

Adonis.js api delete route is not working


I tried to hit a specific route:

http://127.0.0.1:3333/store/products?productId=4

but the server give me this error:

"message": "E_ROUTE_NOT_FOUND: Cannot DELETE:/store/products",

"stack": "HttpException: E_ROUTE_NOT_FOUND: Cannot PATCH:/store/products\n   

Solution

  • You are not hitting the right url and your route is wrong.

    The right url with your route.js is :

    http://127.0.0.1:3333/store/products/4
                                         ^- Product id
    

    and the route :

    Route.delete('/products/:productId', 'ProductsController.delete')
    //                      ^- use : for url parameter
    

    Routing explanation

    Body data & url parameters are totally different.

    Please read : What is the difference between URL parameters and query strings?

    Body data

    Request body (json).

    Documentation : https://preview.adonisjs.com/guides/http/form-submissions#reading-form-data

    Example url :

    http://127.0.0.1:3333/products?name=hello
    

    Route example :

    Route.post('/products', 'MyController.myFunction')
    

    Controller :

    public async myFunction ({ request }: HttpContextContract) {
      const data = request.only(['name'])
      // ...
    }
    

    Url parameter

    Specify dynamic url parameter.

    Documentation : https://preview.adonisjs.com/guides/http/routing#dynamic-urls

    Example url :

    http://127.0.0.1:3333/products/1
    

    Route example :

    Route.post('/products/:id', 'MyController.myFunction')
    

    Controller :

    public async myFunction ({ params }: HttpContextContract) {
      const id = params.id
      // ...
    }