基本 HTTP 请求

基本 HTTP 请求

HTTP 已经被广泛大量使用,尽管 HTTP 有多种请求方式,但是万变不离其宗,我们先以基本的4个请求方法为例子,逐步讲解一下更多的复杂应用场景。

以下例子都会在 controller 代码中对 https://httpbin.org 发起请求来完成。

GET

读取数据几乎都是使用 GET 请求,它是 HTTP 世界最常见的一种,也是最广泛的一种,它的请求参数也是最容易构造的。

// app/controller/npm.js
class NpmController extends Controller {
  async get() {
    const ctx = this.ctx;
    const result = await ctx.curl('https://httpbin.org/get?foo=bar');
    ctx.status = result.status;
    ctx.set(result.headers);
    ctx.body = result.data;
  }
}
  • GET 请求可以不用设置 options.method 参数,HttpClient 的默认 method 会设置为 GET。
  • 返回值 result 会包含 3 个属性:status, headers 和 data
    • status: 响应状态码,如 200, 302, 404, 500 等等
    • headers: 响应头,类似 { 'content-type': 'text/html', ... }
    • data: 响应 body,默认 HttpClient 不会做任何处理,会直接返回 Buffer 类型数据。一旦设置了 options.dataType,HttpClient 将会根据此参数对 data 进行相应的处理。

完整的请求参数 options 和返回值 result 的说明请看下文的 options 参数详解 章节。

POST

创建数据的场景一般来说都会使用 POST 请求,它相对于 GET 来说多了请求 body 这个参数。

以发送 JSON body 的场景举例:

// app/controller/npm.js
class NpmController extends Controller {
  async post() {
    const ctx = this.ctx;
    const result = await ctx.curl('https://httpbin.org/post', {
      // 必须指定 method
      method: 'POST',
      // 通过 contentType 告诉 HttpClient 以 JSON 格式发送
      contentType: 'json',
      data: {
        hello: 'world',
        now: Date.now(),
      },
      // 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
      dataType: 'json',
    });
    ctx.body = result.data;
  }
}

下文还会详细讲解以 POST 实现 Form 表单提交和文件上传的功能。

PUT

PUT 与 POST 类似,它更加适合更新数据和替换数据的语义。除了 method 参数需要设置为 PUT,其他参数几乎跟 POST 一模一样。

// app/controller/npm.js
class NpmController extends Controller {
  async put() {
    const ctx = this.ctx;
    const result = await ctx.curl('https://httpbin.org/put', {
      // 必须指定 method
      method: 'PUT',
      // 通过 contentType 告诉 HttpClient 以 JSON 格式发送
      contentType: 'json',
      data: {
        update: 'foo bar',
      },
      // 明确告诉 HttpClient 以 JSON 格式处理响应 body
      dataType: 'json',
    });
    ctx.body = result.data;
  }
}

DELETE

删除数据会选择 DELETE 请求,它通常可以不需要加请求 body,但是 HttpClient 不会限制。

// app/controller/npm.js
class NpmController extends Controller {
  async del() {
    const ctx = this.ctx;
    const result = await ctx.curl('https://httpbin.org/delete', {
      // 必须指定 method
      method: 'DELETE',
      // 明确告诉 HttpClient 以 JSON 格式处理响应 body
      dataType: 'json',
    });
    ctx.body = result.data;
  }
}