A. Cam
A. Cam

Reputation: 149

Can a POST request accept two callbacks and can the first pass data to the second?

I have the following .post() request:

const express = require('express');
const router = express.Router();
const search_controller = require('../controllers/searchController');
const result_controller = require('../controllers/resultController');

//Search Routes

router.post('/', search_controller.search_create_post);

module.exports = router;


Could I add a second callback to it so that the first callback is run, then the second callback as such:

router.post('/', search_controller.search_create_post, result_controller.result_create_post)

Would I need a next() somewhere in those create functions? And could I also pass data from the search_create_post callback to the result_create_post callback? I would want to pass in the newly created Search object's id.

My current search_controller.search_create_post function is a such:

exports.search_create_post = (req, res, next) => {
    let newSearch = new Search({ search_text: req.body.search_text });

    newSearch.save((err, savedSearch) => {
        if (err) {
            console.log(err);
        } else {
            res.send(savedSearch);
        }
    })
};

Upvotes: 2

Views: 34

Answers (1)

joelnet
joelnet

Reputation: 14231

You might be able to use like this (based on how your functions are written):

// option A
router.post('/', search_controller.search_create_post, result_controller.result_create_post)

// options B
router.post('/', search_controller.search_create_post)
router.post('/', result_controller.result_create_post)

If search needs to pass data to result, you could set req.search_data in search_create_post and then get the value in result_create_post.

Take a look at https://expressjs.com/en/guide/using-middleware.html. There are a few good examples on this page.

app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id)
  next()
}, function (req, res, next) {
  res.send('User Info')
})

// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id)
})

based on your comment below:

You might be able to do this...

exports.search_create_post = (req, res, next) => {
  let newSearch = new Search({ search_text: req.body.search_text });
  newSearch.save((err, savedSearch) => {
    if (err) {
      console.log(err);
    } else {
      req.searchData = savedSearch;
    }
    next();
  })
};

Upvotes: 2

Related Questions