简体   繁体   English

将C#语法HTTP调用转换为JS语法调用

[英]Converting C# syntax HTTP call to JS syntax call

I got an HTTP call implemented with C# which calls to an Azure API:我得到了一个 HTTP 调用,它使用 C# 调用 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.我需要在 Javascript 呼叫中执行相同的呼叫,但我不确定我应该如何发送Authorization header。

Here's what I got so far without the header (question in comment inside the code):这是我在没有 header 的情况下得到的结果(代码中的评论中的问题):

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;
}

As requested, here's your JavaScript code with the header inserted:根据要求,这是插入了 header 的 JavaScript 代码:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM