rimraf
rimraf

Reputation: 4126

Execute a function with parameters passed to an express server?

I want to call a function using the parameters passed to an express call. Here's an example tying to do a simple console.log inside a function called inside the app.get():

// server.js
const express = require('express')
const app = express()
const port = process.env.PORT || 3001

function processRequest(api_key, another_value) {
  console.log(api_key, another_value)
}

app.get('/api', function(req, res) {
  let api_key = req.query.api_key
  let another_value = req.query.another_value
  processRequest(api_key, another_value)
  res.json({api_key, another_value})
})

app.listen(port)
console.log("Started server")

and a simple test

const axios = require('axios')
function test() {
  axios.get('localhost:3001/api?api_key=testkey&another_value=anothervalue', res => console.log(res.data))
}
test()

I know i'm missing something simple here. Thanks ya'll

Upvotes: 2

Views: 48

Answers (1)

Arpit Solanki
Arpit Solanki

Reputation: 9931

Use req.query.somevalue to get query params from request.

req.param only works for URL params like api/distance/:id

Some from docs:

(req.params) Checks route params, ex: /user/:id

(req.query) Checks query string params, ex: ?id=12 Checks urlencoded body params

Upvotes: 1

Related Questions