简体   繁体   中英

Solved - node.js axios.post part with auth is ok but axios.get after that fails

axios.post part is ok and run into console.log('Authenticated') but axios.get part fails because of Authorisation required!

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');
        });
}

axios requests are Promise and not apply until committed.

try to use axios.get() out of previous request.

I think you can use .finally() method of axios for your need.

The same problem. webLogin works great, and if OK, calling getstoveValues() and here i always land in catch block and get 401 Authorisation Problem.

//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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM