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

时间:2016-02-18 05:05:42

标签: node.js rest request

我在使用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'

6 个答案:

答案 0 :(得分:17)

request支持application/x-www-form-urlencodedmultipart/form-data表单上传。对于multipart/related,请参阅multipart API。

application / x-www-form-urlencoded(URL-Encoded Forms)

网址编码表单很简单:

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

答案 1 :(得分:1)

如果您使用axios软件包,这是解决方案。

如果标题为Content-type: 'application/x-www-form-urlencoded'

然后您将调用post API为

const response: any = await axios.post(URL, bodyData,  {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });

URL是您的API网址,例如http // YOUR_HOST / XYZ ...,和

bodyData是要在Post API中发送的数据,

现在您将如何通过它?

假设您将数据作为对象,那么您必须将其编码为url,让我向您展示

let data = {
username: name,
password: password
}

然后您的bodyData将像

let bodyData = `username=${name}&password=${password}`

如果标头是 Content-type: 'application/x-www-form-urlencoded'

如果您有海量数据无法手动编码,则可以使用qs模块

运行命令npm i qs,并在您的文件中

const qs = require('qs');

...

let data = {
username: name,
password: password,
manyMoreKeys: manyMoreValues
} 
 
let bodyData = qs.stringify(data);

答案 2 :(得分:0)

使用节点的查询字符串库将js对象编码为“ URL编码”形式,并将字符串作为请求主体传递。 Documentation

答案 3 :(得分:0)

如果您使用的是package

const got = require('got'); const qs = require('qs');

const postData = { 广告', b:“ b”, c:“ c” };

在异步功能中

const response =等待got.post('url',{ 标头:{ 'Content-Type':'application / x-www-form-urlencoded' }, 正文:qs.stringify(postData) });

答案 4 :(得分:0)

application / x-www-form-urlencoded要求您对您的键和值(MSDN Documentation)进行URL编码。 例如:

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;

答案 5 :(得分:0)

我认为 got package 具有有效的内置功能:

const got = require('got');

const response = await got.post(url, {form: {a: 'd', b: 'b', c: 'c'});