expressjs_使用ExpressJS获取URL和POST参数

expressjs

Often when we are building applications using ExpressJS, we will need to get information from our users.

通常,当我们使用ExpressJS构建应用程序时,我们将需要从用户那里获取信息。

This can happen any number of ways but the two most popular are:

这可以通过多种方式发生,但是最受欢迎的两种方式是:

URL参数 (URL Parameters)

These are information that are passed through the URL like so:

这些是通过URL传递的信息,如下所示:

http://example.com/api/users?id=4&token=sdfa3&geo=us

This is most seen in requesting information from an API.

这在从API请求信息中最为明显。

URL Parameters are grabbed using req.param.variable_name

URL参数使用req.param.variable_name

POST参数 (POST Parameters)

These are information that come from forms. We'll be grabbing from forms that pass information as application/x-www-form-urlencoded.

这些是来自表单的信息。 我们将从传递作为application/x-www-form-urlencoded信息的表单中获取信息。

POST Parameters are grabbed using req.body.variable_name

POST参数使用req.body.variable_name

Let's take a look at how we can grab the parameters using the popular Node.js framework, ExpressJS.

让我们看一下如何使用流行的Node.js框架ExpressJS来获取参数。

示例应用程序进行测试 (Sample App to Test)

We'll be creating a sample application to make sure that grabbing parameters works. We'll also be using POSTman to test the form POST.

我们将创建一个示例应用程序,以确保抓取参数有效。 我们还将使用POSTman测试POST表单。

We'll only need two files:

我们只需要两个文件:

- package.json
- server.js

Here is the package.json

这是package.json

{
  "name": "express-parameters",
  "main": "server.js",
  "dependencies": {
    "express": "~4.10.2"
  }
}

Here's the start of our server.js:

这是我们server.js的开始:

// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

We can now start our server using:

现在,我们可以使用以下命令启动服务器:

$ node server.js

You can also use nodemon server.js if you have nodemon installed so that the server will restart on changes.

如果已安装nodemon server.js也可以使用nodemon server.js ,以便服务器在更改后重新启动。

Now let's create two routes now to test grabbing parameters.

现在让我们创建两条路由来测试抓取参数。

获取任何URL参数 (Getting Any URL Parameter)

For this example, we'll grab a parameter directly from the URL. Let's say we are using the example URL: http://example.com/api/users?id=4&token=sdfa3&geo=us

对于此示例,我们将直接从URL中获取参数。 假设我们使用的是示例网址: http://example.com/api/users?id=4&token=sdfa3&geo=us : http://example.com/api/users?id=4&token=sdfa3&geo=us

The parameters that come out of this will be:

由此产生的参数将是:

id 4
token sdfa3
geo us
ID 4
代币 sdfa3
地缘 我们

It's very easy to grab these parameters. Here's the route and the method for grabbing parameters is req.param().

获取这些参数非常容易。 这是路线,获取参数的方法是req.param()

// routes will go here
app.get('/api/users', function(req, res) {
  var user_id = req.param('id');
  var token = req.param('token');
  var geo = req.param('geo');  

  res.send(user_id + ' ' + token + ' ' + geo);
});

The parameters are naturally passed through the req (request) part. Now if we go to our browser at http://localhost:8080/api/users?id=4&token=sdfa3&geo=us, we'll be able to see the three parameters!

参数自然通过req (请求)部分传递。 现在,如果我们通过http:// localhost:8080 / api / users?id = 4&token = sdfa3&geo = us进入浏览器,我们将能够看到三个参数!

特定参数的特定Craft.io路线 (Specific Routing for Specific Parameters)

We can also name the paramter directly in the route itself. Here's a URL and example:

我们也可以直接在路线本身中命名参数。 这是一个URL和示例:

// http://localhost:8080/api/1
  app.get('/api/:version', function(req, res) {
    res.send(req.params.version);
  });

路由参数中间件 (Route Parameter Middleware)

Next up, we'll be using the Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

接下来,我们将使用Express param函数获取特定参数。 这被认为是中间件,将在调用路由之前运行。

This can be used for validations (like checking if a user exists) or grabbing important information about that user or item.

这可用于验证(例如检查用户是否存在)或获取有关该用户或商品的重要信息。

An example for this would be:

例如:

// parameter middleware that will run before the next routes
app.param('name', function(req, res, next, name) {

    // check if the user with that name exists
    // do some validations
    // add -dude to the name
    var modified = name + '-dude';

    // save name to the request
    req.name = modified;

    next();
});

// http://localhost:8080/api/users/chris
app.get('/api/users/:name', function(req, res) {
    // the user was found and is available in req.user
    res.send('What is up ' + req.name + '!');
});

If we visit the URL in our browser, we'll see:

如果在浏览器中访问该URL,则会看到:

What is up chris-dude!

chris-dude怎么了!

Pretty neat. You can use this param middleware for validations and making sure that information passed through is valid and the correct format.

漂亮整齐。 您可以使用此param中间件进行验证,并确保传递的信息有效且格式正确。

We then save information to the request (req) so that our other route will have access to it.

然后,我们将信息保存到请求( req )中,以便我们的其他路由可以访问它。

Further Reading More Express routing: Learn to Use the Express 4.0 Router

进一步阅读更多Express路由: 了解如何使用Express 4.0 Router

POST参数 (POST Parameters)

To get POST parameters, we'll need two the ExpressJS body-parser package. This will allow us to grab information from the POST.

要获取POST参数,我们需要两个ExpressJS body-parser包。 这将使我们能够从POST中获取信息。

安装人体解析器 (Install body-parser)

We'll need to install body-parser using:

我们需要使用以下命令安装body-parser:

$ npm install body-parser --save

Now that we have that package and it has been added to our package.json thanks to the --save modifier, we have to configure it in our server.js file.

现在我们有了该程序包,并且通过--save修饰符将其添加到package.json ,我们必须在server.js文件中对其进行配置。

Add the following after you define the app variable.

定义app变量后,添加以下内容。

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

With body-parser configured, we can now create our route:

配置了body-parser后,我们现在可以创建路线:

We will grab POST parameters using req.body.variable_name

我们将使用req.body.variable_name获取POST参数

// POST http://localhost:8080/api/users
// parameters sent with 
app.post('/api/users', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

We can test this using POSTman and send information as application/x-www-form-urlencoded:

我们可以使用POSTman进行测试,并以application/x-www-form-urlencoded发送信息:

2014-11-14

结论 (Conclusion)

Those are the quick ways we can grab information using ExpressJS. Grabbing data from the request is an easy enough process.

这些是我们可以使用ExpressJS捕获信息的快速方法。 从请求中获取数据很容易。

Just grab the information quick and easily so that you can move on to building great things!

只需快速轻松地获取信息,您就可以继续构建伟大的事物!

翻译自: https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters

expressjs

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值