简体   繁体   English

如何通过 NodeJS 应用程序传递请求查询参数

[英]How to pass request query parameters through a NodeJS application

I'm currently working on learning NodeJs and am running into a problem with passing query parameters.我目前正在学习 NodeJ,并且遇到了传递查询参数的问题。 The stack consists of express, request-promise, and mongodb.堆栈由 express、request-promise 和 mongodb 组成。 The design of the application I'm shooting for is to have an express.js that is basically the UI app for users.我正在拍摄的应用程序的设计是有一个express.js ,它基本上是用户的 UI 应用程序。 There is also a server.js that defines any REST api endpoints, and a recipes.js that handles running all the queries and any logic I would want.还有一个server.js定义了任何 REST api 端点,还有一个recipes.js处理运行所有查询和我想要的任何逻辑。

Below is the express.js file that I mentioned before that would handle the UI:下面是我之前提到的用于处理 UI 的express.js文件:

// Node imports.
const express = require('express');
const app = express();
const request = require('request');
const rp = require('request-promise');
const url = require('url');

const port = 3001;

// View configuration information.
app.use(express.static('public'));
app.set('view engine', 'ejs');

// Routing.
app.get('/recipes', (req, res) => {
    console.log("TODO(map) In the express.js: " + req.query.count);

    var options = {
    method: 'GET',
    uri: 'http://localhost:3000/recipes',
    json: true
    }

    // Run get and wait on promise before rendering.
    rp(options, (req, res) => {
    }).then((recipes_list) => {
    res.render('index-promise', { pageTitle: 'Recipes', recipes: recipes_list })
    });
})

// Server listening.
app.listen(port, () => {
    console.log('Server listening on http://localhost:' + port);
});

You can see the app has a single URL route for now.您现在可以看到该应用程序只有一个 URL 路由。 The server.js file below shows the API endpoints mentioned above:下面的server.js文件显示了上面提到的 API 端点:

// Node imports.
const url = require('url');
const express = require('express');
const app = express();

const port = 3000;

// API imports.
var recipeApi = require('./apis/recipes.js');

// Routing.
app.get('/recipes', (req, res) => {
    console.log("TODO(map) In the server.js: " + req.query.count);
    recipeApi.getRecipesByCount(req, res);
})

// Server listening.
app.listen(port, () => {
    console.log('Server listening on http://localhost:' + port);
});

The final file, recipes.js , connect to the database and gets the data an kicks it back.最后一个文件recipes.js连接到数据库并获取数据并将其踢回。

// Node imports.
const url = require('url');
const express = require('express');
const app = express();

// Mongo imports.
const MongoClient = require('mongodb').MongoClient;
const Db = require('mongodb').Db
const Server = require('mongodb').Server

// Create a DB object so we can query the db anywhere.
const db = new Db('mydb', new Server('localhost',27017));

/**
 * Function for getting a certain number of recipes.
 * NOTE: The req object should include a "count" query parameter.
 * 
 * req: Request being passed in from the server.js
 * res: Response that will be sent back.
 *
 */
exports.getRecipesByCount = (req, res) =>
{
    console.log("TODO(map) In the recipes.js: " + req.query.count);

    if (!req.query.count)
    {
    req.query.count = 0
    }
    db.open((err, db) => {
    db.collection("recipes").find({}).limit(parseInt(req.query.count)).toArray((err, result) => {
        if (err) throw err;
        res.setHeader('Content-Type', 'application/json');
        res.send(result);
        db.close();
    });
    });

}

So at the end of all this, the issue that I'm running into is in the console.log calls both the server.js and the recipes.js .所以在这一切结束时,我遇到的问题是在console.log中调用server.jsrecipes.js The req.query.count value is undefined despite the fact that the URL I'm hitting is http://localhost:3000/recipes?count=1 .尽管我点击的 URL 是http://localhost:3000/recipes?count=1 ,但req.query.count值是未定义的。 How am I supposed to pass the information the req object has to the other app (the REST API) so I can get that information to the end point and query the database correctly?我应该如何将req对象具有的信息传递给其他应用程序(REST API),以便我可以将该信息传递到端点并正确查询数据库?

Looks like you're sending a request to the backend API on port 3000 with no query params.看起来您正在向端口3000上的后端 API 发送请求,但没有查询参数。 In your express.js file you have:在您的 express.js 文件中,您有:

var options = {
method: 'GET',
uri: 'http://localhost:3000/recipes',
json: true
}

Which, as you can see, has NO query parameters.如您所见,其中没有查询参数。 You need to add the params here.您需要在此处添加参数。 If you change this to the code below it should work:如果您将其更改为下面的代码,它应该可以工作:

var options = {
method: 'GET',
uri: 'http://localhost:3000/recipes?count=' + req.query.count,
json: true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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