Http request: "headers" argument must be a object containing only string keys and string array values

I am attempting to implement a custom authentication function on an app service. This involves verifying the existence of a user using the Graph API in order to authenticate the client.

Code:

exports = async function (payload) {
  const { token } = payload;
  await context.http.get({
      url: 'https://graph.microsoft.com/v1.0/me',
      headers: {
        Authorization: "Bearer " + token,
       "Content-Type": "application/json",
      },
    });
};

Also tried using other dependencies but getting error as below:

Error : Failed to validate token: Not a function: [object Object]
await axios({ method: 'GET', url: 'https://graph.microsoft.com/v1.0/me', headers: { Authorization: 'Bearer ' + token, },

Error: Failed to validate token: ‘get’ is not a function
await axios.get('https://graph.microsoft.com/v1.0/me', { headers: { Authorization: 'Bearer ' + token } });

Hi @Rajan_Braiya,

The values in the headers documents must be arrays. See https://www.mongodb.com/docs/atlas/app-services/services/http-actions/http.get/#parameters for reference. So the correct syntax would be

exports = async function (payload) {
  const { token } = payload;
  await context.http.get({
      url: 'https://graph.microsoft.com/v1.0/me',
      headers: {
        Authorization: [ "Bearer " + token ],
       "Content-Type": [ "application/json" ],
      },
    });
};

Hi @Kiro_Morkos, Thank you very much for your reply. I am first time using mongoDB function,

using your code solve that error. but still don’t know why its not returning the data, current received output:


> result: 
{
  "$undefined": true
}
> result (JavaScript): 
EJSON.parse('{"$undefined":true}')

I am already using this function in express and working fine. node-js Code:

const checkToken = async (req, res, next) => {
  try {
    const { data } = await axios.get("https://graph.microsoft.com/v1.0/me", {
      headers: {
        Authorization: `Bearer ${bearerToken}`,
      },
    });
    req.user = data;
    next();
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Error while retrieving user information" });
  }
};

Given the snippet that you shared in the original post, it appears that you’re not returning anything from the function. If you want to return the result of the HTTP request, you could do something like the following:

const res = await context.http.get( ... );
const body = JSON.parse(res.body.text());
return body;

You’ll also want to ensure you implement proper error handling (wrap the request in try/catch, check the returned status code, etc.)

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.