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

rah*_*hul 10 rest request node.js

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

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'      
    }   
};
Run Code Online (Sandbox Code Playgroud)

并且发布请求是:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

在其余的api中,据说请求体应该是:

username='provide user name in url encoded
format'&password= "provide password in url encoded format'
Run Code Online (Sandbox Code Playgroud)

Edu*_*omo 19

request支持application/x-www-form-urlencodedmultipart/form-data表单上传.有关multipart/related参考multipart API的信息.

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

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) { /* ... */ })
Run Code Online (Sandbox Code Playgroud)

请参阅: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(...);
Run Code Online (Sandbox Code Playgroud)

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

  • 此评论不再适用。“request”模块被标记为已弃用。https://github.com/request/request/issues/3142 (3认同)

Uğu*_*han 7

使用node的URLSearchParams类将js对象编码为“url编码”形式,并将字符串作为请求体传递。 文档


小智 5

如果您使用 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'
                }
            });
Run Code Online (Sandbox Code Playgroud)

URL 是您的 API url,例如 http//YOUR_HOST/XYZ...,并且

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

现在你将如何通过它?

假设你有数据作为对象,所以你必须将其编码为 url,让我向你展示

let data = {
username: name,
password: password
}
Run Code Online (Sandbox Code Playgroud)

那么你的 bodyData 就会像

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

如果 header 是,则可以通过这种方式在正文中传递数据 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);
Run Code Online (Sandbox Code Playgroud)


Kea*_*che 5

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

data:`${encodeURI('username')}=${encodeURI('xyzzzzz')}&${encodeURI('password')}=${encodeURI('abc12345')}`
Run Code Online (Sandbox Code Playgroud)

正如@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;
Run Code Online (Sandbox Code Playgroud)