Home > Net >  Node.JS - How to pass a variable to my API function?
Node.JS - How to pass a variable to my API function?

Time:11-14

I have created a very simple API based on two files as follows:

api.js

import express from 'express';
const app = express();
import { getWhereToApi} from './lib/handlers.js';
const port = 3000;

app.get('/api/vacations', getWhereToApi);

app.listen(port, function() {
    console.log(`Express started in ${app.get('env')} `  
      `mode on http://127.0.0.1:${port}`  
      `; press Ctrl-C to terminate.`)});

handlers.js

var whereTo = {
    "GRU": {
        "destinations": ["MAD", "LAX", "MEX"],},
    "LAX": {
        "destinations": ["NYC", "GRU", "MEX"],},
    "NYC": {
        "destinations": ["LAX"],},
}

export async function getWhereToApi(req, res, iata){
    res.json(whereTo[iata]);
}

I want to be able to pass the IATA as var somehow (e.g. "GRU"), so I would get the following result:

{
  "destinations": [
    "MAD",
    "LAX",
    "MEX"
  ]
}

How can I do it? Thank you!

CodePudding user response:

If you want to put the data in the query string as in:

http://127.0.0.1:3000/api/vacations?iata=GRU

Then the value will be in req.query.

export function getWhereToApi(req, res){
    const iata = req.query.iata;
    const data = whereTo[iata];
    if (data) { 
        res.json(data);
    } else {
        res.sendStatus(404);   // value not found
    }
}

CodePudding user response:

@Bob, going by the use case, you can expect the iata from the params of the API. In handlers.js file in getWhereToApi() function you could extract it using const iata = req.params.iata; way, as following

export async function getWhereToApi(req, res){
    const iata = req.params.iata 
    res.json(whereTo[iata]);
}

I think of this as the simplest way.

  • Related