web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Small and medium business | Business Central, N...
Suggested Answer

Error while getting Business Central API token using Javascript

(1) ShareShare
ReportReport
Posted on by 40
Hello,
 
I'm able to get Business Central API token using Postman.
 
I copied the Javascript Fetch code from the Postman but it is giving an error: net::ERR_ABORTED 400 (Bad Request)
 
Here's my code:
 
function  getToken() { 
	  

    const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Cookie", "fpc=AhfVR-owHAtPqR9lisIjqfqlCTnCAQAAAGxj094OAAAA; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");

const urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");
urlencoded.append("scope", "https://api.businesscentral.dynamics.com/.default");
urlencoded.append("client_id", "my client id");
urlencoded.append("client_secret", "my client secret");

const requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: urlencoded,
  redirect: "follow",
  mode: 'no-cors'
};

fetch("https://login.microsoftonline.com/tenantid/oauth2/v2.0/token", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
 .catch((error) => console.error(error));
}
Can someone tell me what I'm doing wrong here.
 
Thanks,
Priyank
I have the same question (0)
  • Gerardo Rentería García Profile Picture
    25,555 Most Valuable Professional on at
    Hi
    i hope this can help you
    Best
    GR
  • Suggested answer
    YUN ZHU Profile Picture
    99,086 Super User 2026 Season 1 on at
    Hi, hope the following helps as well.
     
    Thanks.
    ZHU
  • Suggested answer
    Saif Ali Sabri Profile Picture
    2,354 Moderator on at

    AI was used to create this answer

    Your code contains a few issues that need to be resolved for it to properly fetch the token from Azure AD.


    1. mode: 'no-cors' Issue

    The no-cors mode prevents JavaScript from seeing the response content due to browser security policies. When using no-cors, the browser restricts the request to only a limited set of safe headers, methods, and body types, which breaks your API call. Since you're working with an authentication endpoint, no-cors mode is not appropriate.

    Solution:
    Remove mode: 'no-cors' entirely from the requestOptions. The default mode (cors) will work for this scenario if the endpoint allows cross-origin requests.


    2. Incorrect Content-Type for the Request Body

    The Content-Type header specifies the format of the data in the request body. Since you’re sending URLSearchParams as the body, the correct Content-Type is application/x-www-form-urlencoded, which you’ve already set correctly. However, ensure that URLSearchParams is properly serialized.


    3. Ensure Proper URL and Parameters

    Make sure you are replacing placeholders like "tenantid", "my client id", and "my client secret" with actual values.

    • https://login.microsoftonline.com/tenantid/oauth2/v2.0/token → Replace tenantid with your Azure Active Directory (AAD) tenant ID.
    • Verify your client_id and client_secret match the app registration in Azure AD.

    4. Handling the Response Properly

    The response from Azure AD is JSON, not plain text, so you need to parse it as JSON using .json() instead of .text().


    5. Debugging CORS and Cross-Origin Issues

    The browser might block the request due to CORS policy if the endpoint doesn't allow requests from your domain. To test this without being blocked:

    • Use Postman or a similar tool to confirm that the request works outside the browser.
    • If CORS issues persist, you may need to set up a server-side proxy or handle authentication on a backend to avoid browser limitations.

    Fixed Code

    Here’s your corrected JavaScript code:

     
    javascript
    function getToken() {
    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

    const urlencoded = new URLSearchParams();
    urlencoded.append("grant_type", "client_credentials");
    urlencoded.append("scope", "https://api.businesscentral.dynamics.com/.default");
    urlencoded.append("client_id", "your-client-id"); // Replace with your actual client ID
    urlencoded.append("client_secret", "your-client-secret"); // Replace with your actual client secret

    const requestOptions = {
    method: "POST",
    headers: myHeaders,
    body: urlencoded,
    redirect: "follow",
    };

    fetch("https://login.microsoftonline.com/your-tenant-id/oauth2/v2.0/token", requestOptions) // Replace 'your-tenant-id'
    .then((response) => {
    if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
    })
    .then((result) => console.log(result)) // Token will appear here
    .catch((error) => console.error("Error:", error));
    }

    Additional Notes:

    1. Test in a Local Development Environment

      • If you’re running this code in a browser and facing CORS issues, consider testing it first in Node.js (outside the browser) or using Postman. This can help confirm whether the issue is with the request setup or browser limitations.
    2. Environment Variables for Secrets

      • Avoid hardcoding client_id and client_secret directly in the code. Use environment variables or a secure way to store them to prevent accidental exposure.
    3. Error Handling

      • The error handling logic (if (!response.ok)) ensures that you catch HTTP errors and don't blindly try to parse the response if it’s invalid.
    4. Token Expiration

      • The token you retrieve will expire after a certain period (usually 1 hour). Make sure to implement token caching or re-fetch the token when necessary.

    Common Debugging Steps

    • Verify that the AAD App Registration (Azure Portal) has the necessary API permissions for Business Central.

      • API Permission: Delegated or Application access to Dynamics 365 Business Central.
      • Grant admin consent after setting the permissions.
    • Double-check the tenant_id, client_id, and client_secret are correct and correspond to the app registration.

    • Ensure the app registration allows client_credentials flow in its Authentication settings.

  • Suggested answer
    Khushbu Rajvi. Profile Picture
    22,130 Super User 2026 Season 1 on at

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the March Top 10 Community Leaders

These are the community rock stars!

Leaderboard > Small and medium business | Business Central, NAV, RMS

#1
OussamaSabbouh Profile Picture

OussamaSabbouh 1,993 Super User 2026 Season 1

#2
YUN ZHU Profile Picture

YUN ZHU 1,116 Super User 2026 Season 1

#3
Khushbu Rajvi. Profile Picture

Khushbu Rajvi. 557 Super User 2026 Season 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans