POSTing with JSON using npm request

2020-07-09 02:45发布

问题:

How would one do the following with the request npm module?

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) {
  ...
});

回答1:

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.



回答2:

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

it's working



回答3:

Pretty sure that demo is equivalent to: 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.