1

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!

2
  • 1
    Where do you expect the iata value to come from? The way you have it configured now, you're expecting Express to provide it when it calls the route handler, but that isn't going to happen the way you show it. Where is it supposed to come from? Do you want it to be in the URL? If so, show how you want it in the URL? Commented Nov 13, 2021 at 9:42
  • Thanks for the comment. From a querystring for example? 127.0.0.1:3000/api/vacations?iata=GRU Commented Nov 13, 2021 at 9:44

2 Answers 2

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

@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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.