API 如果 API 输出中存在特殊字符,使用 axios 的调用将失败

API call with axios fails if special characters are present in the API output

我目前正在使用 node.js 创建 Alexa Skill,并加载了版本为 0.21.1 的 axios。 如果查询的 API returns 正常字符,则一切正常。但是,如果有 &,则调用失败。为什么要这样做?

这是我的代码:

const name = 'example';
    
const apiUrl= function() {
   return `https://example.com/${name}`
}
    
const APIRequest = async (url) => {
    try {
        const { data } = await axios.get(url);
        return data;
    } catch (error) {
        console.error('cannot fetch quotes', error);
    }
};

const APIHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest'
        && handlerInput.requestEnvelope.request.intent.name === 'APIIntent'
    },
    async handle(handlerInput) {
        try {
            const [Data] = await Promise.all([
                (APIRequest(apiUrl()))
            ]);
            const speechText = `Data 1: ${Data.1}, Data 2: ${Data.2}`;
            return handlerInput.responseBuilder
              .speak(speechText)
              .getResponse();
        } catch (error) {
            return handlerInput.responseBuilder
              .speak('Unfortunately I do not know at the moment')
              .getResponse();
        }
    },
};

这是API输出

作品:

{
    "1": "this is a text",
    "2": "this is a text"
}

无效:

{
    "1": "this is a text & more information",
    "2": "this is a text"
}

使用 nodejs 为 alexa skill 编码,我的假设是你可能正在使用 AWS lambda 这样做,在这种情况下我建议使用 lambda local or serverless

我知道如果您不使用上述选项将很难调试。

我对你的问题有两个建议,

第一个: Axios 拦截器。尽管我个人没有机会在 Alexa 技能开发中使用它,但它很有可能会起作用。

axios.interceptors.response.use(response => {
    let data = response.headers["content-type"];
    if (data.includes("charset=ISO-8859-1")) {
        responsee.data = data.decode(response.data, 'ISO-8859-1');
    }
    return response;
});

参考:- https://github.com/axios/axios/issues/332

第二种方法:编码响应并将response.data解码为所需格式

使用iso-8859-2

const response = await axios.request({
  method: 'GET',
  url: 'https://www.test.com',
  responseType: 'arraybuffer',
  responseEncoding: 'binary'
});

让结果 = iso88592.decode(response.data.toString('binary'));