簡體   English   中英

如何在 node.js 中發布內容類型 ='application/x-www-form-urlencoded' 的數據

[英]how to post data in node.js with content type ='application/x-www-form-urlencoded'

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

request支持application/x-www-form-urlencodedmultipart/form-data表單上傳。 對於multipart/related請參閱 multipart 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

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;

使用節點的 URLSearchParams 類將 js 對象編碼為“url 編碼”形式並將字符串作為請求正文傳遞。 文檔

如果您使用的是 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 是像 http//YOUR_HOST/XYZ... 這樣的 API url,並且

bodyData 是您要在 post API 中發送的數據,

現在你將如何通過它?

假設你有數據作為對象,所以你必須將它編碼為 url,讓我展示給你

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

那么你的 bodyData 會像

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

如果標題是Content-type: 'application/x-www-form-urlencoded'這是您可以在正文中傳遞數據的方式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);

如果您使用的是got 包

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

const body = qs.stringify({
    a: 'd',
    b: 'b',
    c: 'c',
});

在異步函數中

const response = await got.post(url, { body });

如果 Content-Type 標頭不存在,它將被設置為 application/x-www-form-urlencoded

我認為got 包具有有效的內置功能:

const got = require('got');

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM