Search code examples
javascriptc#http-headersfetchdotnet-httpclient

Converting C# syntax HTTP call to JS syntax call


I got an HTTP call implemented with C# which calls to an Azure API:

public async Task<string> CheckPipelineRunStatus(string pipelineId, string pipelineRunId, CancellationToken cancellationToken = default)
    {
        string responseBody = "";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(
                    System.Text.ASCIIEncoding.ASCII.GetBytes(
                        string.Format("{0}:{1}", "", _token))));

            var requestUrl = $"https://dev.azure.com/{_organization}/{_project}/_apis/pipelines/{pipelineId}/runs/{pipelineRunId}?api-version={_api_version}";

            using (HttpResponseMessage response = await client.GetAsync(requestUrl, cancellationToken))
            {
                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();
            }
        }
        return responseBody;
    }

I need to do the same call in a Javascript call and I'm not sure how exactly am I suppose to send the Authorization header.

Here's what I got so far without the header (question in comment inside the code):

async function checkPipelineStatus(url)
{
    var params =  { 
        method: 'GET',
        headers: { 
            'Content-Type': 'application/json',
             //is the auth supposed to be here? what to do with that 64base string?
        }
    };
    const fetchResult = await fetch(url, params);
    const result = await fetchResult.text();
    if (!fetchResult.ok) 
    {
       throw result;
    }
    return result;
}

Solution

  • As requested, here's your JavaScript code with the header inserted:

    async function checkPipelineStatus(url)
    {
        let base64Credentials = btoa(':' + _token);
        var params =  { 
            method: 'GET',
            headers: { 
                'Content-Type': 'application/json',
                // Insert your own Base64 credentials here:
                'Authorization': `Basic ${base64Credentials}`
            }
        };
        const fetchResult = await fetch(url, params);
        const result = await fetchResult.text();
        if (!fetchResult.ok) 
        {
           throw result;
        }
        return result;
    }