HTTP 请求
简单的 HTTP 请求
Midway 内置了一个简单的 HTTP 请求客户端,无需引入三方包即可使用。
默认 Get 请求,返回数据为 Buffer。
内置的 Http 客户端只提供最简单的能力,仅满足大部分的前端接口数据获取,如需复杂的功能,比如文件上传等,请使用其他的客户端,如 fetch,axios,got 等。
简单方法形式
import { makeHttpRequest } from '@midwayjs/core';
const result = await makeHttpRequest('http://127.1:7001/');
// Buffer.isBuffer(result.data) => true
Get 请求,带上 Query,返回类型为 JSON。
import { makeHttpRequest } from '@midwayjs/core';
const result = await makeHttpRequest('http://127.1:7001/', {
data: {
a: 1,
b: 2
},
dataType: 'json', // 返回的数据格式
});
// typeof result.data => 'object'
// result.data.url => /?a=1&b=2
可以指定类型
import { makeHttpRequest } from '@midwayjs/core';
const result = await makeHttpRequest('http://127.1:7001/', {
method: 'GET',
dataType: 'json',
});
返回 text 格式。
import { makeHttpRequest } from '@midwayjs/core';
const result = await makeHttpRequest('http://127.1:7001/', {
method: 'GET',
dataType: 'text',
});
POST 请求并返回 JSON。
import { makeHttpRequest } from '@midwayjs/core';
const result = await makeHttpRequest('http://127.1:7001/', {
method: 'POST',
data: {
a: 1,
b: 2
},
dataType: 'json',
contentType:'json', // 发送的 post 为 json
});
// result.data ...
警告
注意,请不要在请求中直接返回 result 对象,result 对象是标准的 httpResponse,在大部分场景下无法被直接序列化,会抛出对象循环的错误。
设置请求超时时间。
import { makeHttpRequest } from '@midwayjs/core';
let err;
// 超时会报错,注意 catch
try {
const result = await makeHttpRequest('http://127.1:7001/', {
method: 'GET',
dataType: 'text',
timeout: 500,
});
} catch (e) {
err = e;
}
实例形式
import { HttpClient } from '@midwayjs/core';
const httpclient = new HttpClient();
const result = await httpclient.request('http://127.1:7001/');
// Buffer.isBuffer(result.data) => true
和方法形式参数相同。
import { HttpClient } from '@midwayjs/core';
const httpclient = new HttpClient();
const result = await httpclient.request('http://127.1:7001/', {
method: 'POST',
data: {
a: 1,
b: 2
},
dataType: 'json',
contentType:'json', // 发送的 post 为 json
});
// result.data ...
示例形式,可以复用创建出的对象,并且每次请求,都可以带上一些固定的参数,比如 header。
import { HttpClient } from '@midwayjs/core';
const httpclient = new HttpClient({
headers: {
'x-timeout': '5'
},
method: 'POST',
timeout: 2000
});
// 每次都会带上 headers
const result = await httpclient.request('http://127.1:7001/');