Search code examples
node.jsexpressodata

Node.js pass Basic Authorization to odata service


I have a backend using Node.js with Express and it is reaching out to an Odata service to retrieve some data.

To do so it is using "odata": "^1.3.1" : https://www.npmjs.com/package/odata/v/1.3.1

However, the service requires I pass Basic Authentication in the request.

I do not see anywhere in their documentation on how to do so. Below is my call to the service within a route, how can I add Basic Authentication to the request?

const express = require("express");
const router = express.Router();
const o = require('odata').o;

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;

router.get('/otasks', function(req, res) {
    o(process.env.ODATA_SERVER)
        .get()
        .query()
        .then(data => res.json({ payload: data }))
        .catch(error => {
            console.log(error);
            return res.json({ payload: "error" });
        });
});

module.exports = router;

Solution

  • Basic access authentication: When the user agent wants to send authentication credentials to the server, it may use the Authorization header field. Reference

    According to the package document, you can provide headers to your request. Then your logic code will become like this:

    ...
    o(process.env.ODATA_SERVER, {
        headers: { 'Authorization': `Basic ${Buffer.from('username:password').toString('base64')}` },
    })
    ...