Hanley Soilsmith
Hanley Soilsmith

Reputation: 629

How to pass data between two 'app.post' methods on a server? (node/express)

I have an express server that receives a .post containing a json. I need to use the data from the initial .post for a call to a different API.

How to pass data received from one API call and use it in a different API call?

Here is the code, this is part of a chain of API calls with quite a bit more logic, but I have simplified it here for clarity.

Server receives data:

app.post("/pay", (req, res) =>{
  const userInput = req.body.userInput
}

A different API needs to use userInput:

app.post("/reply", (req, res) =>{
  console.log(userInput)}

Any ideas?

Upvotes: 0

Views: 117

Answers (1)

vapurrmaid
vapurrmaid

Reputation: 2307

If you want to hit multiple functions on the same server, just register them as consecutive middleware. The middleware are called in order from left to right. Use next() to call the next handler.

app.post('/pay', handler1, handler2....)

When doing this, you'll often find it's useful to extract your handlers (often called controllers) so that they can be unit tested and called elsewhere:

example controller:

const makePayment = (req, res, next) => {
  // handler logic
}

const createUser = (req, res, next) => {
  // handler logic
}

module.exports = {
  makePayment,
  createUser
}

Router:

import Controllers from '<path to controllers>'
app.post('/pay', Controllers.makePayment, Controllers.createUser)

This will work so long as they can execute serially. If the functionalities depend on each other (such as requiring the result from another), you can extract those functionalities and call them directly:

import { myMethod } from <path to method>
app.post('/post', (req, res, next) => {
  myMethod(req.body.userInput)
})

If you are calling an API from a different server, then within your request handler you can use your http client of choice to send a request from your server to their endpoint.

Here's an example using axios:

app.post('/pay', async (req, res, next) => {
  const data = await axios.post('their_endpoint', {
    data: req.body.userInput
  })

  // rest of handler
})

Upvotes: 1

Related Questions