直接請求
可直接在后端模擬 form-data 上傳文件番刊,請求第三方服務(wù)堂鲤,上代碼:
const stream = await this.ctx.getFileStream()
const form = new FormStream()
Object.keys(stream.fields).forEach(key => form.field(key, stream.fields[key])) // 用戶附帶參數(shù)
form.stream(stream.fieldname, stream, stream.filename)
const res = await this.app.curl(`${url}`, {
method: 'POST',
dataType: 'json',
headers: {
...form.headers(),
},
stream: form,
timeout: 8000,
})
// ... console.log(res)
能上傳成功的前提是 對方服務(wù)端接口必須支持文件流
代理轉(zhuǎn)發(fā)
需要安裝插件 @eggjs/http-proxy
npm i @eggjs/http-proxy --save
配置 plugin.js
// {app_root}/config/plugin.js
exports.httpProxy = {
enable: true,
package: '@eggjs/http-proxy',
};
service:
const res = await this.ctx.proxyRequest('xxx.com', {
rewrite(urlObj) {
urlObj.pathname = '/upload'
return urlObj
},
withCredentials: true, // if true, will send cookie when cors
headers: {
cookie, // 可不攜帶贱呐,視目標(biāo)接口而定
},
})
// console.log(res)
// 控制臺打印如下視為成功
// [-/::1/-/198ms POST /api/v1/dw/upload] forward:success, status:200, targetUrl:http://xxx.com/upload
這種方式還可以實現(xiàn)node做中間層代理轉(zhuǎn)發(fā)的目的得哆,包括任何http請求醋火。