简体   繁体   English

使用请求模块发布表单数据 - Nodejs & Express

[英]Posting form data using request module - Nodejs & Express

I'm using a platform for data security, and they have this code snippet showing how to post data to their platform:我正在使用一个数据安全平台,他们有这个代码片段显示如何将数据发布到他们的平台:

They're using the request module: https://github.com/mikeal/request他们正在使用请求模块: https://github.com/mikeal/request

const request = require('request');

request({
    url: 'https://mypass.testproxy.com/post',
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({'secret' : 'secret_value'})
  }, function(error, response, body){
    if(error) {
      console.log(error);
    } else {
      console.log('Status:', response.statusCode);
      console.log(JSON.parse(body));
    }
});

It works fine, but I wanted to replace the 'secret': 'secret_value' object with my form data, but I'm having a hard time figuring out how to do this.它工作正常,但我想用我的表单数据替换 'secret': 'secret_value' object,但我很难弄清楚如何做到这一点。 The only way I know how to retrieve form data is with req.body:我知道如何检索表单数据的唯一方法是使用 req.body:

function(req, res) {
var form = {
  card_number: req.body.card_number,
  card_cvv: req.body.cvv,
  card_expirationDate: req.body.card_expirationDate,
};
    // ...
});

How would I do that?我该怎么做? Any help is greatly appreciated.任何帮助是极大的赞赏。

I know the code below is wrong, but that's the idea of what I want to achieve:我知道下面的代码是错误的,但这就是我想要实现的想法:

request( function(req, res) {
var form = {
  card_number: req.body.card_number,
  card_cvv: req.body.cvv,
  card_expirationDate: req.body.card_expirationDate,
};{
    url: 'https://mypass.testproxy.com/post',
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(form)
...```



The form data will be sent with the content type application/x-www-form-urlencoded eg card_number=123&cvv=456 .表单数据将使用内容类型application/x-www-form-urlencoded发送,例如card_number=123&cvv=456

Express has a middleware to parse that https://expressjs.com/en/api.html#express.urlencoded Express 有一个中间件来解析https://expressjs.com/en/api.html#express.urlencoded

app.use(express.urlencoded());

The parsed values will be in req.body in your post route.解析后的值将在您的 post 路由中的req.body中。 So eg req.body.card_number will contain the value 123 .因此,例如req.body.card_number将包含值123

You can put the request inside the route:您可以将请求放入路由中:

app.post('/', function (req, res) {
  var form = { /* ... */ }
  request({
    body: JSON.stringify(form),
    /* ... */
  })
})

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

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