node.jsexpress

get parameter from url or body for API call


I am testing a 3rd party API with hardcoded data, but I would like to grab this parameter from the url or a text field.

Example url: http://localhost:3300/track

Here is the code that is retrieving the desired data from the 3rd party API:

const getCarrier = require('ts-tracking-number')

//const trackingNumber = require('ts-tracking-number')
//This is where we need to make our 3rd party api call

function httpGetCarrier (req, res) {
    const trackNo = '633973126310'
    const tracking = getCarrier.getTracking(trackNo);
                                            
    console.log(tracking.courier.code)
    return res.status(200).json(tracking.courier.code)
   
}

module.exports = { httpGetCarrier } 

Instead of passing a hardcoded "tracking number" to variable 'trackNo', I would like to grab this number from the url like this: http://localhost:3300/track/633973126310

How do I get this value from the req object? This is probably pretty straight forward but I'm just learning. If it's very simple, please also show me how I could get the same value from a text field in the body of an html page.

Thank you!


Solution

  • Declare in the route name :

    app.get('/<entrypoint>/:trackNo', httpGetCarrier)
    

    and use the query parameter into your controller :

    const trackNo = req.params.trackNo