开发者社区> 问答> 正文

EMAS Serverless的云函数支持导入axios进行网络请求吗?

由于接口返回的是二进制数据,需要通过responseType将body设置为arraybuffer再返回给前端,而云函数自带的ctx.httpProxyClient貌似并不能指定responseType,所以只能通过第三方库进行请求。

展开
收起
游客gxs2dqcxxkia2 2023-05-26 23:12:23 181 0
4 条回答
写回答
取消 提交回答
  • EMAS Serverless 的云函数是支持导入和使用 axios 进行网络请求的。你可以在云函数中使用类似下面的代码进行请求,并在请求参数中指定 responseType 为 'arraybuffer',来将接口返回的二进制数据作为 ArrayBuffer 类型返回给前端。

    const axios = require('axios');
    
    exports.handler = async function(request, response, context) { 
      const url = 'https://example.com/api';
      const config = {
        responseType: 'arraybuffer'
      };
    
      try {
        const axiosResponse = await axios.get(url, config);
        const data = axiosResponse.data;
        return data;
      } catch (error) {
        console.error(error);
      }
    }
    

    需要注意的是,EMAS Serverless 环境中的云函数运行在 Node.js 环境下,因此需要使用 Node.js 版本的 axios 库,而不是在浏览器中使用的那个。可以使用 npm install axios 命令将 axios 库安装到你的项目中。

    2023-05-27 08:44:23
    赞同 展开评论 打赏
  • 云端行者觅知音, 技术前沿我独行。 前言探索无边界, 阿里风光引我情。

    是的,EMAS Serverless的云函数支持导入axios进行网络请求。您可以在云函数中使用npm安装axios,然后在代码中导入axios模块,进行网络请求。在axios的请求配置中,您可以设置responseType为arraybuffer以获取二进制数据。

    2023-05-27 08:06:44
    赞同 展开评论 打赏
  • 是的,EMAS Serverless 的云函数支持导入 axios 进行网络请求。你可以在云函数代码中使用 "axios" 库进行网络请求,根据需要设置responseType为 "arraybuffer"。

    示例代码:

    const axios = require('axios');
    
    exports.handler = async function(event, context) {
      try {
        const response = await axios.get('https://example.com', {
          responseType: 'arraybuffer'
        });
        return response.data;
      } catch (error) {
        console.error(error);
        return null;
      }
    }
    
    2023-05-27 08:06:40
    赞同 展开评论 打赏
  • 确实,云函数自带的ctx.httpProxyClient并不支持设置responseType,但可以通过第三方库axios来实现请求返回arraybuffer类型的数据,具体代码如下:

    const axios = require('axios');
    
    exports.main = async (event, context) => {
      const url = 'http://example.com/api';
      const config = {
        method: 'get',
        url: url,
        responseType: 'arraybuffer'
      };
      const response = await axios(config);
      return response.data;
    };
    
    

    在上述代码中,我们使用了axios库来发起请求,并将responseType设置为'arraybuffer',这样就可以正确地返回二进制数据了。需要注意的是,由于使用了第三方库,需要在云函数的package.json中添加相应的依赖,例如:

    {
      "dependencies": {
        "axios": ".21.1"
      }
    }
    
    
    2023-05-27 08:06:39
    赞同 展开评论 打赏
来源圈子
更多
收录在圈子:
基于阿里巴巴以及合作伙伴的最佳实践,围绕大前端、云原生领域的相关技术热点(小程序、Serverless、应用中间件、低代码、DevOps)展开行业探讨,与开发者一起探寻云原生时代应用研发的新范式。
相关文档: 移动研发平台
问答排行榜
最热
最新

相关电子书

更多
Hologres Serverless之路:揭秘弹性计算组 立即下载
Serverless开发平台: 让研发效能再提升 立即下载
Serverless 引领云上研发新范式 立即下载