cancel
Showing results for 
Search instead for 
Did you mean: 
Subscribe

Hello everyone, 

I want to call an ODATA Endpoint of my RAP Service in my On Premise System, which is exposed via Cloud Connector in BTP
First, I have to fetch the 'x-csrf-token' via axios.get. Therefore, I encoded my username and password and add it to basic authentication. I receive a token from the response headers. With that token in the header I request my Entity, but after that I always get an error:  401 Not authorized

 

 

const axios = require("axios");

const sTokenUrl = "https://MYSYSTEMURL:MYPORT/sap/opu/odata/sap/MYSERVICE";
const sBase64UserNamePassword = "USERNAME:PASSWORD"; // This is Base64Encoded
const sServiceUrl = "https://MYSYSTEMURL:MYPORT/sap/opu/odata/sap/MYSERVICE/MYENTITY"

const oTokenResponse = await axios.get(sTokenUrl, {
            headers: {
                "x-csrf-token": "fetch",
                Authorization: `Basic ${sBase64UserNamePassword}`,
                Accept: "*/*",
                "Cache-Control": "no-cache",
                "Accept-Encoding": "gzip, deflate, br",
                Connection: "keep-alive",
            },
            withCredentials: true,
        });

const aCookies = oTokenResponse.headers["set-cookie"];
const sAuthToken = oTokenResponse.headers["x-csrf-token"];
const oHeaders = {
   "X-Csrf-Token": sAuthToken, 
   Accept: req.headers.accept,
   "Content-Type": req.headers["content-type"] ?? "application/json",
   "Cookie": aCookies.join(";")
};
try {
   const response = await axios.get(sServiceUrl, { headers: oHeaders });
} catch (oError) {
    console.log("Request Error:", oError.message);                   
}

 

 

If I do the same thing with Postman, it works. Can anybody help me with that ? 

Thanks
Daniel

 

View Entire Topic
zaunaro
Explorer
0 Likes

I found the answer. 

It was the change from axios to https. I did the request as following. Now it works for me.

const oHeaders = {
   "X-Csrf-Token": sAuthToken,
   Accept: req.headers.accept,
   "Content-Type": req.headers["content-type"] ?? "application/json",
   Cookie: aCookies.join(";"),
};

const response = await makeHttpsRequest({
                        method: "GET",
                        hostname: new URL(sUrl).hostname,
                        path: new URL(sUrl).pathname,
                        headers: oHeaders,
                    });

const makeHttpsRequest = (options, postData = null) => {
    return new Promise((resolve, reject) => {
        const req = https.request(options, res => {
            let data = "";
            res.on("data", chunk => (data += chunk));
            res.on("end", () => {
                resolve({
                    status: res.statusCode,
                    headers: res.headers,
                    data: data,
                });
            });
        });

        req.on("error", err => reject(err));
        if (postData) req.write(postData);
        req.end();
    });
};