如何使用内容类型 ='application/x-www-form-urlencoded' 在 node.js 中发布数据

新手上路,请多包涵

我在使用 Content-type: 'application/x-www-form-urlencoded' 在 node.js 中发布数据时遇到问题

var loginArgs = {
    data: 'username="xyzzzzz"&"password="abc12345#"',

    //data: {
    //    'username': "xyzzzzz",
    //    'password': "abc12345#",
    //},

    headers: {
            'User-Agent': 'MYAPI',
            'Accept': 'application/json',
            'Content-Type':'application/x-www-form-urlencoded'
    }
};

发布请求是:

 client.post("http:/url/rest/login", loginArgs, function(data, response){
console.log(loginArgs);

if (response.statusCode == 200) {
    console.log('succesfully logged in, session:', data.msg);
}

它总是返回 用户名/密码 不正确。

在其余 api 中,据说请求正文应该是:

 username='provide user name in url encoded
format'&password= "provide password in url encoded format'

原文由 rahul 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 835
2 个回答

request 支持 application/x-www-form-urlencodedmultipart/form-data 表单上传。对于 multipart/related 参考多部分 API。

application/x-www-form-urlencoded(URL 编码表单)

URL 编码的表单很简单:

 const request = require('request');

request.post('http:/url/rest/login', {
  form: {
    username: 'xyzzzzz',
    password: 'abc12345#'
  }
})
// or
request.post('http:/url/rest/login').form({
  username: 'xyzzzzz',
  password: 'abc12345#'
})
// or
request.post({
  url: 'http:/url/rest/login',
  form: {
    username: 'xyzzzzz',
    password: 'abc12345#'
  }
}, function (err, httpResponse, body) { /* ... */ })

见: https ://github.com/request/request#forms

或者,使用 request-promise

 const rp = require('request-promise');
rp.post('http:/url/rest/login', {
  form: {
    username: 'xyzzzzz',
    password: 'abc12345#'
  }
}).then(...);

请参阅: https ://github.com/request/request-promise#api-in-detail

原文由 Eduardo Cuomo 发布,翻译遵循 CC BY-SA 3.0 许可协议

application/x-www-form-urlencoded 要求您对键和值进行 URL 编码( MSDN 文档)。举例说明:

 data:`${encodeURI('username')}=${encodeURI('xyzzzzz')}&${encodeURI('password')}=${encodeURI('abc12345')}`

正如@Bram 评论的那样, 请求库已被弃用

我将要编写的示例将使用 NodeJS 附带的标准 HTTPS 库。

您可以将其编写如下(打字稿):

 import * as https from 'https';
// import * as http from 'http'; // For HTTP instead of HTTPS

export class ApiExample {

    // tslint:disable-next-line: no-empty
    constructor() { }

    public async postLogin(username: string, password: string): Promise<any> {
        // application/x-www-form-urlencoded requires the syntax "UrlEncodedKey=UrlEncodedValue&UrlEncodedKey2=UrlEncodedValue2"
        const xFormBody = `${encodeURI('username')}=${encodeURI(username)}&${encodeURI('password')}=${encodeURI(password)}`;

        return this.performRequest(xFormBody)
    }

    private performRequest(requestBody: string) {
        return new Promise((resolve, reject) => {

            const options: https.RequestOptions = {
                hostname: 'example.url.com',
                port: 443,
                path: '/login',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': Buffer.byteLength(requestBody)
                }
            };

            // const req = http.request(options, function (res) { // For HTTP
            const req = https.request(options, function (res) {
                // This may need to be modified based on your server's response.
                res.setEncoding('utf8');

                let responseBody = '';

                // Build JSON string from response chunks.
                res.on('data', (chunk) => responseBody = responseBody + chunk);
                res.on('end', function () {
                    const parsedBody = JSON.parse(responseBody + '');

                    // Resolve or reject based on status code.
                    res.statusCode !== 200 ? reject(parsedBody) : resolve(parsedBody);
                });
            });

            // Make sure to write the request body.
            req.write(requestBody);
            req.end();
            req.on('error', function (e) { reject(e); });
        });
    }
}

export default ApiExample;

原文由 KeaganFouche 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题