【问题标题】:How to do javascript request (supertest, superagent) behaving like curl --data-binary如何做javascript请求(supertest,superagent)表现得像curl --data-binary
【发布时间】:2018-03-12 11:25:23
【问题描述】:

tl;博士; 发送以下 curl 有效,但我不能在 supertest 中做同样的事情(包装 superagent https://github.com/visionmedia/superagent/

curl 'http://local/api/items' -X DELETE -H 'Accept-Encoding: gzip, deflate' -H 'content-type: application/json;charset=UTF-8' --data-binary '"1234"'

我可以从网络界面中删除项目,并在其中附加所需文本的文件。
然后使用开发工具提取了上面介绍的 curl 命令,这很有魅力。
如何在js中执行?
试过了:

const response = yield request('http://local')
      .delete('/api/items')     
      .set('Accept-Encoding', 'gzip, deflate')    
      .set('Content-Type', 'application/json;charset=UTF-8')
      .send("1234");

然后我得到 "status":400,"error":"BodyNotReadable",
也许使用write 可以是一个答案,但我不知道该怎么做。
可用选项的完整列表https://github.com/visionmedia/superagent/blob/master/lib/node/index.js

【问题讨论】:

    标签: javascript curl request supertest superagent


    【解决方案1】:

    试试:

    request
      .delete('http://url/')
      .set('Accept-Encoding', 'gzip, deflate')
      .set('Content-Type', 'application/json;charset=UTF-8')
      .send(JSON.stringify(body))
      .type('json')
      .then(response => {
          console.log(response)
      })
      .catch(error => {
          console.log(error)
      });

    关键是JSON.stringify要发送的有效载荷。应该可以。

    【讨论】:

      【解决方案2】:

      你可以试试这个吗:

      request('http://local')
        .delete('/api/items')
        .set('Accept-Encoding', 'gzip, deflate')
        .set('Content-Type', 'application/json;charset=UTF-8')
        .write("1234")
        .end((err, res) => {
          // Get response here
        });
      

      【讨论】:

      • 得到了`TypeError: request(...).delete(...).set(...).set(...).write(...).end 不是一个函数`
      • 请问你的超级代理是什么版本的?
      • v: SuperAgent 3.5
      • 你能测试一下 request.del('local/api/items', '1234', (err, res) => { // 在这里获取响应 }).set('Accept-Encoding', ' gzip, deflate') .set('Content-Type', 'application/json;charset=UTF-8');
      猜你喜欢
      • 2016-11-13
      • 2018-12-28
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2014-02-01
      • 2016-05-28
      • 2013-07-14
      相关资源
      最近更新 更多