Search code examples
javascriptnode.jsazure-devopsaxiosazure-devops-rest-api

how to fetch azure Devops work Item details from Node Js


I have a Node JS app, which used to create and fetch azure DevOps ticket. So create method is working fine and ticket created at DevOps but when try to fetch ticket details , it shows an error. My fetch method is below,where I am passing title of work item and try to retrieve all the details from Azure DevOps.

async function getWorkItemIdByTitle(workItemTitle) {
    let status = "";
    console.log("getting work item ID")
    console.log(workItemTitle);
    try {
        // Encode the title for the URL
        const encodedTitle = encodeURIComponent(workItemTitle);

        // Construct the query URL to search for work items by title
        const url = `${orgUrl}/${projectNameForURL}/_apis/wit/wiql?api-version=7.1`;

        // WIQL (Work Item Query Language) query to search for work items by title
        const wiqlQuery = `SELECT [System.Id] FROM WorkItems WHERE [System.Title] = '${encodedTitle}'`;

        const response = await axios.post(url, { query: wiqlQuery }, {
            headers: {
                'Content-Type': 'application/json-patch+json',
                'Authorization': `Basic ${Buffer.from(`:${pat}`).toString('base64')}`,
            },
        });

        // Check if any work items were found
        if (response.data.workItems.length > 0) {
            const workItemId = response.data.workItems[0].id;
            console.log(`Work item ID for title '${workItemTitle}': ${workItemId}`);
            status = "Incident Number: " + workItemId;
        } else {
            console.log(`No work item found with title '${workItemTitle}'`);
            status = "No matching incidents found"
        }
    } catch (error) {
        console.error('Error retrieving work item by title:', error.response ? error.response.data : error.message);
        status = "Error fetching incidents";
    }
    console.log("STATUS: ", status);
    return status;
}

and error I am getting is below: error message

I am new to this, any help will be thankful.


Solution

  • The TF400898 error is caused by the wrong 'Content-Type' you set to the headers. The right 'Content-Type' should be 'application/json' instead of 'application/json-patch+json'.

    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${Buffer.from(`:${pat}`).toString('base64')}`,
    }
    

    In addition, you should not encode the work item title passed into the function, it will let the WIQL cannot get the actual string of the title and causes the work item cannot be found.

    const wiqlQuery = `SELECT [System.Id] FROM WorkItems WHERE [System.Title] = '${workItemTitle}'`;