Is it possible for a POST request to handle multiple callbacks, with the ability for the first callback to pass data to the

I have a question about my .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;


Is it possible to add a second callback to the request in order to run both callbacks sequentially, like this:

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

Do I need to use next() inside those create functions? And can I pass data from the search_create_post callback to the result_create_post callback? Specifically, I would like to pass the id of the newly created Search object.

This is my current

search_controller.search_create_post
function:

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);
        }
    })
};

Answer №1

Consider using the following code snippets based on the structure of your functions:

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

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

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

Refer to https://expressjs.com/en/guide/using-middleware.html for additional examples.

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 that displays the user ID
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id)
})

Based on your comment below:

You may want to try this approach...

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();
  })
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty erasing the existing input

I'm trying to create a form input field in JavaScript that generates a specified number of additional inputs based on user input. The issue I'm facing is that while the code works and adds more input fields, it does not delete the previously gene ...

After removing an item from the array, React fails to display the updated render

As a newcomer, I am struggling with a particular issue. I have implemented a delete button for each item in a list. When the button is clicked, the object in the firstItems array is successfully deleted (as confirmed by logging the array to the console), b ...

Creating a functional dropdown form in Ruby On Rails: A Step-by-Step Guide

Having an issue with implementing a dropdown form in the navigation bar of my Rails application. The problem arises randomly - sometimes it works smoothly, while other times I have to refresh the page for it to function properly. The Rails version being u ...

Tips for effectively handling 404 errors when loading directive templates in AngularJS

When working with an AngularJS directive, the templateUrl parameter is dynamically specified. 'templates/' + content_id + '.html' I am looking for a way to handle situations where the value of content_id may not be valid or result in ...

Updating the HTML class with JavaScript

My HTML class has two classes $(document).ready(function() { $(".container").hover(function() { $('.green').addClass('display-on'); }); $(".container").mouseleave(function() { $('.black&apos ...

Obtaining the value right after initializing useState in React

Currently, I am utilizing the useState hook within my functional component in React. However, I find myself puzzled by a particular issue. [myRoom,setMyRoom] = useState('test1'); Whenever I try to use the setMyRoom function to update the value ...

Substitute Digits within Text

I am currently attempting to remove or replace multiple characters from a string that I have retrieved from Sharepoint. The values extracted from Sharepoint seem to contain ID information that I need to eliminate. Although the sharepointPlus Script is unab ...

Guide to transferring array information from one Vuejs route to another

I'm facing an issue with passing an array from one Vuejs route to another. Specifically, I need to pass the array from home.vue to post.vue. In my route.js file for post.vue, I have: { path: '/post/:cart', name: 'post', com ...

unable to utilize the library three.js

I stumbled upon an interesting animation on Codepen that uses blocks to reconstruct a map image. The necessary JavaScript files are three.min.js and TweenMax.min.js. I copied the links from Codepen and pasted them into my HTML using <script src="">&l ...

Does Internet Explorer 10 support the FormData object?

I've developed a JavaScript app that enables me to upload images asynchronously, and it works seamlessly in most browsers. However, the infamous Internet Explorer is causing some trouble... To address this issue, I devised a workaround for IE9- versi ...

What is the name of the undefined JSON object and how can I retrieve its parameters?

After sending a request to a web server, I received the following response: The response, when using JSON.stringify, appears as shown below: undefined{\"access_token\":\"Rhazjww5 ...QUiTMVc\",\"token_type\":\"bearer&bs ...

Ways to utilize jQuery for intricate forms in place of RJS

Within the 74th episode of Railscasts, Ryan demonstrates the process of executing intricate forms with RJS. Check it out here: The key here is to generate a partial and incorporate it using RJS. This episode is quite dated and back then, jQuery may not ha ...

The NodeJs backend is not being recognized by the React app

Having trouble integrating a Node.js backend with my React JS app initialized with Vite. When I add the index.js file and run the command, only the React part initializes and does not recognize posts and express routes. Can anyone assist? Here are my App.j ...

The azure-graph platform has detected a Request_BadRequest error due to an invalid domain name being included in the

I am attempting to use Node.js to retrieve the user object based on its ID. Below is the code I have written: const MsRest = require('ms-rest-azure'); const credentials = await MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, ke ...

NodeJS - Assertion failure in callback function does not cause Mocha unit test to fail

I am currently facing an issue while running Mocha unit tests on a NodeJS application, specifically with handling assertions within callback functions. As an example, consider the following unit test: describe('PDF manipulation', () => { ...

What is the best way to make an ajax commenting system function from a separate directory?

I am facing an issue with implementing an ajax commenting system on my website. When I place all the code from the /comment directory directly in the root, everything works fine and the commenting system functions as expected on new pages. However, when I ...

`Manipulating the image source attribute upon clicking`

I need help changing the attr: { src: ...} binding of an img element when a different image is clicked. Here is an example: $(document).ready(function () { var viewModel = { list: ko.observableArray(), showRenderTimes: ...

Is there a way to verify if a button has been clicked in node.js?

I need to determine if a button has been clicked and then display a new HTML file. I am currently using the express.js app.get method to open my HTML files. Can someone please explain how I can direct a button click to open a new HTML file in the same br ...

Fade in and out animation for flash notifications

Is there a way to create a flash message with a smooth fade in and out animation using jQuery? I would appreciate any recommendations on the most efficient approach for achieving this effect. ...

Creating custom mesh Morph Target Animations using THREE.js

I'm currently working on creating an animation that showcases the revolution of a 2D function around an axis to produce a 3D surface. Successfully rendering the surface, my next task is to implement the animation section using MorphTargets. Despite m ...