【问题标题】:Axios request GET and after some json modifying make POSTAxios 请求 GET 并在一些 json 修改后生成 POST
【发布时间】:2021-12-05 04:27:43
【问题描述】:

我正在尝试向 twilio 发出 GET 请求以从特定渠道获取数据,之后我需要对其进行一些更改,然后再次发布。

我是全新的 js 工作人员,我将不胜感激任何建议 我没有使用 Twilio SDK

到目前为止,我做了这个..但它没有发出帖子请求

function modifyChannel(sid, json) {
    console.log(json);
    return new Promise((resolve, reject) => {
        let newJson = JSON.parse(json.attributes);
        newJson.task_sid = null;
        json.attributes = JSON.stringify(newJson);
        resolve(json);
    })
}

function postChannel(sid, json) {
        axios({
            method: 'post',
            url:`https://chat.twilio.com/v2/Services/${DEV_CREDENTIAL.programmableChatSid}/Channels/${sid}`,
            
            auth: {
                username: DEV_CREDENTIAL.account,
                password: DEV_CREDENTIAL.token
            },

            data: {
                json
            }
        });
}

axios({
    method: 'get',
    url:`https://chat.twilio.com/v2/Services/${DEV_CREDENTIAL.programmableChatSid}/Channels/${channel_sid}`,
    auth: {
        username: DEV_CREDENTIAL.account,
        password: DEV_CREDENTIAL.token
    }
})
.then(response => {
    return modifyChannel(channel_sid, response.data);
}).then(jsonModified => { postChannel(channel_sid, jsonModified); })
.catch(err => console.log(err));

【问题讨论】:

    标签: javascript axios request twilio


    【解决方案1】:

    这里是 Twilio 开发者宣传员。

    我认为问题在于您在发出发布请求时传递了data: { json }。这将扩展到:data: { json: { THE_ACTUAL_DATA }},您只需要 data: { THE_ACTUAL_DATA }。所以,从那里删除 json 键。

    您还可以通过数据操作来简化事情。您没有在 modifyChannel 函数中执行任何异步操作,因此无需返回 Promise。

    请尝试以下方法:

    function modifyChannel(sid, json) {
      let newJson = JSON.parse(json.attributes);
      newJson.task_sid = null;
      json.attributes = JSON.stringify(newJson);
      return json;
    }
    
    function postChannel(sid, json) {
      axios({
        method: "post",
        url: `https://chat.twilio.com/v2/Services/${DEV_CREDENTIAL.programmableChatSid}/Channels/${sid}`,
        auth: {
          username: DEV_CREDENTIAL.account,
          password: DEV_CREDENTIAL.token,
        },
        data: json,
      });
    }
    
    axios({
      method: "get",
      url: `https://chat.twilio.com/v2/Services/${DEV_CREDENTIAL.programmableChatSid}/Channels/${channel_sid}`,
      auth: {
        username: DEV_CREDENTIAL.account,
        password: DEV_CREDENTIAL.token,
      },
    })
      .then((response) => {
        const jsonModified = modifyChannel(channel_sid, response.data);
        postChannel(channel_sid, jsonModified);
      })
      .catch((err) => console.log(err));
    

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 2018-12-05
      • 2021-05-03
      • 2020-06-20
      • 2014-07-24
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多