简体   繁体   中英

Node.js and MySQL - 2 unrelated queries to the same page

My question is a 2 parter:

  1. I have an express.js file the shows a form. The form needs to pull 2 different queries from the db. One to create a select drop-down and one to create check-boxes. How can I send 2 (or more) unrelated queries to the same page from my node.js file?

  2. Since I'm using

    app.post('/results',urlencodedParser,function(req, res) {

The page is redirected to localhost:3000/results . Then git shows there is no such page (even though there is a page called results.ejs in my views folder. what am I doing wrong?

I can't answer your second question w/o more info (though, to be frank it should be a separate question in any case).

As for the first question, there's a few ways to skin that cat. Myself, I decide based on reuse. Are the lists that create the select and the checkbox group going to be used elsewhere, or just on this page?

If just on this page, I'd probably use something like the async library's parallel() function or Promise.all to run both queries and return the result sets that way.

If it's going to be reused, I'd package them as middleware and then attach the results to the request or to the req.locals object.

Async version would look something like this:

const async = require('async');

// later, in your handler

app.get('/results', function(req,res){
   async.parallel({
     checkboxes : checkboxQueryFn,
     selectList : selectListQueryFn
   }, (e, bothQueries) => {
      // if either query errored, you'll get an 'e' object here, otherwise bothQueries will be an object where bothQueries.checkboxes will have the results of that query and bothQueries.selectList will have the results of that one. 
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM