【问题标题】:How to write HTTP request for using third party API?如何编写使用第三方 API 的 HTTP 请求?
【发布时间】:2021-05-31 17:52:14
【问题描述】:

背景

我在一个小型私有 JavaScript+HTML 项目中,我正在尝试使用 HTML PDF API。此 API 提供将 HTML 字符串转换为 PDF 文件的过程。 但是,作为工程方​​面的新手,缺乏关于 HTTP、Web、API、服务器端编程的知识和经验,我很难知道如何才能实现我的目标。

问题

我尝试了一个 curl sn-p,它显示在 this usage page 中,展示了如何访问 API 并从 html 字符串生成 pdf。

[从 HTML 字符串生成 PDF]

curl -H 'Authentication: Token <your token>' \
-d 'html=<h1>HTML PDF API is cool!</h1>' \
'https://htmlpdfapi.com/api/v1/pdf' > result.pdf

我试过了,它在我的终端上运行。但是,the site 没有显示在 JavaScript (node.js) 代码中使用它的任何示例。

所以,看来我必须自己研究方法,要点可能如下:

  • 了解一般 HTTP 请求格式,并记下 HTTP 请求,其中包含上面 curl sn -p 中编写的内容。
  • 将 HTTP 请求重写为 JSON 格式。
  • 编写用于与 API 站点进行 HTTP 通信的 JavaScript (node.js) 代码,并包含上面的请求 JSON 对象。

但是,由于我的能力不足,我找不到包含实现上述三个里程碑的信息最少的文章。

你能给我一些好的文章或提示吗?

任何信息将不胜感激。

进展

我搜索并尝试使用superagent 使用以下代码向HTML PDF API 发出HTTP 请求。

var request = require('superagent');

request.post('https://htmlpdfapi.com/api/v1/pdf')
   .send({Authentication: "Token <my token>",
          html:"<h1>HTML PDF API is cool!</h1>"
        })
   .end(function(res){
     if (res.ok) {
       console.log(res.body.name);
     } else {
       console.log('error');
       console.log(res);
     }
});

但是,结果是 401 错误,如下所示:

Error: Unauthorized
    at Request.callback (C:\Users\myName\node_modules\superagent\lib\node\index.js:883:15)
    at IncomingMessage.<anonymous> (C:\Users\myName\node_modules\superagent\lib\node\index.js:1127:20)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  status: 401,
  response: <ref *1> Response {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      headers: [Object],
      rawHeaders: [Array],
      trailers: {},
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 401,
      statusMessage: 'Unauthorized',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [ClientRequest],
      text: 'Token missing.',
      [Symbol(kCapture)]: false,
      [Symbol(RequestTimeout)]: undefined
    },
    request: Request {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      _enableHttp2: false,
      _agent: false,
      _formData: null,
      method: 'POST',
      url: 'https://htmlpdfapi.com/api/v1/pdf',
      _header: [Object],
      header: [Object],
      writable: true,
      _redirects: 0,
      _maxRedirects: 5,
      cookies: '',
      qs: {},
      _query: [],
      qsRaw: [],
      _redirectList: [],
      _streamRequest: false,
      _data: [Object],
      req: [ClientRequest],
      protocol: 'https:',
      host: 'htmlpdfapi.com',
      _endCalled: true,
      _callback: [Function (anonymous)],
      res: [IncomingMessage],
      _resBuffered: true,
      response: [Circular *1],
      called: true,
      [Symbol(kCapture)]: false
    },
    req: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 99,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      _header: 'POST /api/v1/pdf HTTP/1.1\r\n' +
        'Host: htmlpdfapi.com\r\n' +
        'Accept-Encoding: gzip, deflate\r\n' +
        'Content-Type: application/json\r\n' +
        'Content-Length: 99\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/api/v1/pdf',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'htmlpdfapi.com',
      protocol: 'https:',
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    text: 'Token missing.',
    body: {},
    files: undefined,
    buffered: true,
    headers: {
      server: 'nginx',
      date: 'Mon, 31 May 2021 09:36:23 GMT',
      'content-type': 'text/plain; charset=utf-8',
      'content-length': '14',
      connection: 'close',
      'x-powered-by': 'Express',
      etag: 'W/"e-6MRs7J3ixq1Oxcy3SHuOU96JCDo"'
    },
    header: {
      server: 'nginx',
      date: 'Mon, 31 May 2021 09:36:23 GMT',
      'content-type': 'text/plain; charset=utf-8',
      'content-length': '14',
      connection: 'close',
      'x-powered-by': 'Express',
      etag: 'W/"e-6MRs7J3ixq1Oxcy3SHuOU96JCDo"'
    },
    statusCode: 401,
    status: 401,
    statusType: 4,
    info: false,
    ok: false,
    redirect: false,
    clientError: true,
    serverError: false,
    error: Error: cannot POST /api/v1/pdf (401)
        at Response.toError (C:\Users\myName\node_modules\superagent\lib\node\response.js:98:13)
        at ResponseBase._setStatusProperties (C:\Users\myName\node_modules\superagent\lib\response-base.js:119:48)
        at new Response (C:\Users\myName\node_modules\superagent\lib\node\response.js:44:8)
        at Request._emitResponse (C:\Users\myName\node_modules\superagent\lib\node\index.js:930:18)
        at IncomingMessage.<anonymous> (C:\Users\myName\node_modules\superagent\lib\node\index.js:1127:42)
        at IncomingMessage.emit (events.js:327:22)
        at endReadableNT (internal/streams/readable.js:1327:12)
        at processTicksAndRejections (internal/process/task_queues.js:80:21) {
      status: 401,
      text: 'Token missing.',
      method: 'POST',
      path: '/api/v1/pdf'
    },
    created: false,
    accepted: false,
    noContent: false,
    badRequest: false,
    unauthorized: true,
    notAcceptable: false,
    forbidden: false,
    notFound: false,
    unprocessableEntity: false,
    type: 'text/plain',
    charset: 'utf-8',
    links: {},
    setEncoding: [Function: bound ],
    redirects: [],
    pipe: [Function (anonymous)],
    [Symbol(kCapture)]: false
  }
}

怎么了?任何信息将不胜感激。

【问题讨论】:

标签: javascript node.js api http curl


【解决方案1】:

您还没有足够仔细地了解 cURL 正在做什么。

curl -H 'Authentication: Token <your token>' \
-d 'html=<h1>HTML PDF API is cool!</h1>' \
'https://htmlpdfapi.com/api/v1/pdf' > result.pdf

-H 是一个标头,您可以使用the set method 添加到超级代理。

-d 是请求正文,它是application/x-www-form-urlencoded 编码的,而不是 JSON 编码的。所以,as per the docs 你需要传递字符串而不是对象。

request.post('https://htmlpdfapi.com/api/v1/pdf')
    .set('Authentication', 'Token <your token>')
    .send('html=<h1>HTML PDF API is cool!</h1>')
    .then(callback, errorCallback);

【讨论】:

  • 谢谢。现在我知道在这种情况下不能使用 JSON。但是,我尝试了您的 sn-p,但它返回“未定义回调”。你知道发生了什么吗?
  • 您没有定义callback 函数,该函数作为示例最后一行的then 的第一个参数传递。
  • 谢谢。我自己设置了callback和errorCallback,效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多