axios.post 与 auth 部分可以,但 axios.get 之后失败

问题描述 投票:0回答:3

axios.post 部分正常并运行到 console.log('Authenticated') 但是 axios.get 部分由于需要授权而失败!

const axios = require('axios');

webLogin();

function webLogin() {
    var API_SERVER = 'https://a-site-with-api-functions';
    var email = 'myemail';
    var password = 'mypassword';

    axios.post(API_SERVER + '/web/login', { email, password }, { withCredentials: true })
    .then(function(response) {
            //appears every time im running this code, because authentication ist successful
             console.log('Authenticated');
            
            //but following part is failing because of Authorisation required!
             axios.get(API_SERVER + '/api/client/12345678/status', { withCredentials: true })

           }).catch(function(error) {
             console.log('Error on Authentication');
        });
}
javascript node.js axios
3个回答
0
投票

axios 请求是

Promise
并且在提交之前不适用。

尝试使用之前请求中的

axios.get()

我认为你可以使用axios的

.finally()
方法来满足你的需要。


0
投票

同样的问题。 webLogin 工作得很好,如果可以的话,调用 getstoveValues() ,在这里我总是陷入 catch 块并得到 401 授权问题。

//vars API_SERVER and so on defined here...

webLogin();


function webLogin() {
    try {
        const response = await axios.post(API_SERVER + '/web/login', { email, password }, { withCredentials: true });
        // in response steht jetzt die Antwort
        // wenn du sie außerhalb der Funktion nutzen willst:
        // return response; // oder einen Teil davon
        this.log.info('webLogin OK')
        
        //getstoveValues aufrufen, wenn webLogin OK
        getstoveValues();
    } catch (e) {
        // fehler behandeln/loggen
        this.log.error('webLogin' + e.message);
    }
}

function getstoveValues() {
    try {
        const response2 = axios.get(API_SERVER + '/api/client/12345678/status', { withCredentials: true })
        // in response steht jetzt die Antwort
        // wenn du sie außerhalb der Funktion nutzen willst:
        // return response; // oder einen Teil davon
        this.log.info(JSON.stringify(response2.data));
    } catch (e) {
        // fehler behandeln/loggen
        this.log.error('getstoveValues: ' + e.message);
    }
}

0
投票

已解决 - 对于 Node.js 我需要这个: https://github.com/3846masa/axios-cookiejar-support#usage

© www.soinside.com 2019 - 2024. All rights reserved.