微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我的 Twilio 函数无法在 JSON REST API 中获取报价

如何解决我的 Twilio 函数无法在 JSON REST API 中获取报价

我只想在此链接 https://quotes.rest/qod.json获取一些特定的引号,但它不起作用。 我复制了本教程 https://youtu.be/wohjl01HZuY 中的代码,但它对我不起作用。我想从 json 链接获得的报价不适用于下面的函数。谁能帮我? :)

exports.handler = function(context,event,callback) {
    const fs = require('fs');
    fs('https://quotes.rest/qod.json').then(response =>{
        const qotd = JSON.parse(response.body);
        let quote = qotd.contents.quotes[0];
        callback(null,quote);
    });
};

解决方法

这里是 Twilio 开发者布道者。

正如 user3761325 指出的那样,fs 是 Node.js 文件系统模块,不会发出 HTTP 请求。有许多库可以轻松地在 Node.js 中发出 HTTP 请求,我个人喜欢 got

创建此视频时,got 模块实际上在 Twilio Functions 中默认可用,但现在已不再如此。您需要将 got 安装到函数依赖项中。您可以查看the documentation for adding dependencies to your Twilio Function here

一旦您将 got 添加到您的依赖项中,您就可以要求 got 并使用它来发出视频中的请求:

const got = require("got");

exports.handler = function(context,event,callback) {
    got('https://quotes.rest/qod.json').then(response =>{
        const qotd = JSON.parse(response.body);
        let quote = qotd.contents.quotes[0];
        callback(null,quote);
    });
};

您可以对 node-fetchaxios 执行相同操作。

,

原谅我,但据我所知,FS 模块 表示文件系统模块。

试试这个代码,这就是你应该如何发送 HTTP 请求。

let handler = function (context,callback) {
  fetch('https://quotes.rest/qod.json')
    .then(response => response.json())
    .then(data => {
      const gotd = data;
      console.log(gotd);
      //Your codes Goes Here
    });
}
handler()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。