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

标签 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'

最佳答案

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

关于node.js - 如何在 node.js 中发布内容类型为 ='application/x-www-form-urlencoded' 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35473265/

相关文章:

javascript - Node.js 服务请求安全网站

javascript - 这是什么时间格式,如何将其转换为纪元?

Node.js 命令行脚本有时不会终止

angularjs - express 4 : How do I send JSON object to view?

c# - 如何返回 C# 对象而不是数组 JSON

node.js - 有必要使用nodeexpress检查url中的参数吗?

Java REST api http方法类型来调用执行sql删除查询的存储过程

mongodb - Nodejs - websocket-node 模块 : How to make multi-client socket-server works?

java - 从java代码访问Apache的unique_id

php - 仅在 safari 浏览器上出现错误请求