如何使用axios npm软件包进行身份验证

时间:2019-02-09 19:47:38

标签: node.js aws-lambda axios

过去,我使用一些php代码查询这样的api

$str = file_get_contents('https://bla:bla@bla.com/rest/api/content/2950446?expand=body.storage');
$jsonObj = json_decode($str, true);

现在我想使用nodejs来构建alexa技能

我对此进行了测试

var session_url = 'https://bla.com/rest/api/content/2950446';


const fetchQuotes = async () => {
    try {
        const { data } = await axios.post(session_url, {}, {
            auth: {
                username: 'bla',
                password: 'bla'
            }});
        return data;
    } catch (error) {
        console.error('cannot fetch quotes', error);
    }
};
根据我的理解,

应该这样做。是这样吗?该URL被调用,但是出现身份验证错误...

1 个答案:

答案 0 :(得分:1)

致电data时,您将options放在axios.post字段中。您的数据必须是axios.post的第二个参数,而不是第三个。

执行axios.post(url, {}, { somethingHere }时,您的data等于{}(空对象)。您应该改用axios.post(url, { somethingHere }, { config },而config部分是可选的。

正确的参数顺序

const fetchQuotes = async () => {
    try {
        const { data } = await axios.post(session_url, {
            auth: {
                username: 'bla',
                password: 'bla'
            }});
        return data;
    } catch (error) {
        console.error('cannot fetch quotes', error);
    }
};