node.js 使用 npm 请求使用 JSON 进行 POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30904808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:52:27  来源:igfitidea点击:

POSTing with JSON using npm request

node.jsoauthrequest

提问by Kirby Kohlmorgen

How would one do the following with the requestnpm module?

如何使用requestnpm 模块执行以下操作?

curl https://todoist.com/oauth/access_token \
    -d client_id=0123456789abcdef \
    -d client_secret=secret \
    -d code=abcdef \
    -d redirect_uri=https://example.com

I've tried doing this:

我试过这样做:

var body = JSON.stringify({ 
  client_id: '0123456789abcdef', 
  client_secret: 'secret', 
  code: 'abcdef'
});

var postBody = {
  url: 'https://todoist.com/oauth/access_token',
  body: body,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
};

request.post(postBody, function(error, response, body) {
  ...
});

回答by BlackMamba

const formData = {
   client_id:     '0123456789abcdef', 
   client_secret: 'secret', 
   code:          'abcdef'
};

request.post(
  {
    url: 'https://todoist.com/oauth/access_token',
    form: formData
  },
  function (err, httpResponse, body) {
    console.log(err, body);
  }
);

Please try this code.

请试试这个代码。

回答by Sajeenthiran

var url = 'http://xxxxx'
request({
  url : url,
  method :"POST",
  headers : {
    "content-type": "application/json",
  },
  body: {
    'id':1,
    'name':'xxxx'
  },
  json: true
},

it's working

它在工作

回答by Calebmer

Prettysure that demo is equivalent to: https://todoist.com/oauth/access_token?client_id=0123456789abcdef&client_secret=secret&code=abcdef&redirect_uri=...

确定该演示相当于: https://todoist.com/oauth/access_token?client_id=0123456789abcdef&client_secret=secret&code=abcdef&redirect_uri=...

Where a ?starts the parameters and an &separates them.

其中 a?开始参数并 a&将它们分开。