【问题标题】:Pass curl options to node js http request将 curl 选项传递给节点 js http 请求
【发布时间】:2015-11-04 23:07:13
【问题描述】:

我有一个对 api 的 curl 请求,它需要一个 -u 参数来设置用户名登录和一个 -d 来发送帖子的数据。

这是一个模板:

$ curl -i -X POST "https://onfleet.com/api/v2/workers" \
     -u "c64f80ba83d7cfce8ae74f51e263ce93:" \
     -d '{"name":"Marco Emery","image":"http://cdn3.addy.co/images/marco.png","phone":"415-342-0112","teams":["0pgyktD5f3RpV3gfGZn9HPIt"],"vehicle":{"type":"CAR","description":"Tesla Model 3","licensePlate":"CA 2LOV733","color":"purple"}}'

如何将 -u 和 -d 转换为以这种方式格式化的节点 js 请求?

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

或者,是否有可能有一个我可以提供给我的网络浏览器的 url 来考虑这些选项?

【问题讨论】:

  • 你试过node-curl 吗? '-u' 可以替换为基本授权标头。示例:Authorization: Basic c64f80ba83d7cfce8ae74f51e263ce93:

标签: javascript node.js api http curl


【解决方案1】:

从 API 文档来看,它使用基本的 HTTP 身份验证,其中密钥字符串是请求的用户名,密码为空。因此,您必须在每个请求中使用该 Authorization 标头。您可以使用request 来执行此操作:

var request = require('request');
var options = {
    method: 'POST',
    uri: 'https://onfleet.com/api/v2/workers',
    body: '{"name":"Marco Emery","image":"http://cdn3.addy.co/images/marco.png","phone":"415-342-0112","teams":["0pgyktD5f3RpV3gfGZn9HPIt"],"vehicle":{"type":"CAR","description":"Tesla Model 3","licensePlate":"CA 2LOV733","color":"purple"}}',
    headers: {
        'Authorization': 'Basic ' + new Buffer("c64f80ba83d7cfce8ae74f51e263ce93:").toString('base64')
    }
};
request(options, function(error, response, body) {
    console.log(body);
});

【讨论】:

  • 是的,这就是我需要的!谢谢你:)
【解决方案2】:

您可以像这样使用superagent npm 模块来执行此操作:

var request = require('superagent');
request
   .post('https://onfleet.com/api/v2/workers')
   .auth('c64f80ba83d7cfce8ae74f51e263ce93', '')
   .send({"name":"Marco Emery","image":"http://cdn3.addy.co/images/marco.png","phone":"415-342-0112","teams":["0pgyktD5f3RpV3gfGZn9HPIt"],"vehicle":{"type":"CAR","description":"Tesla Model 3","licensePlate":"CA 2LOV733","color":"purple"}})
   .end(function(err, res){
         if (res.ok) {
             console.log('yay got ' + JSON.stringify(res.body));
          } else {
             console.log('Oh no! error ' + res.text);
          }
   });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多