Home > other >  simple api with basic auth
simple api with basic auth

Time:01-04

I have:

const https = require('https');
const axios = require('axios');

exports.getEvents = async (req, res) => {

    const httpsAgent = new https.Agent({
        rejectUnauthorized: false,
    });

    try {
      await axios.get('http://localhost/api/events',
      { 
        httpsAgent,
        auth: {
          username: "senstar",
          password: "senstar"
        }
      }).then(resp => {
        res.json(resp.data);
      });
    } catch (error) {
      console.error(error);
    }
}

this's a simple api, I test http://localhost/api/events' on postman, using Authorization: Basic Auth and work it. So I implement the function getEvents to get the results on node js, but this's not working, why? what's wrong? with basic auth?

CodePudding user response:

Try this code

const https = require('https');
const axios = require('axios');
const base64 = require('base-64');

exports.getEvents = async (req, res) => {
    try {
        await axios.get('https://127.0.0.1/api/events',
            {
                headers: {
                    'Authorization': 'Basic '   base64.encode("senstar"   ":"   "senstar")
                }
            }).then(resp => {
                res.json(resp.data);
            });
    } catch (error) {
        console.error(error);
    }
}
  • Related