Search code examples
javascriptc#.netasp.net-corejson.net

How to call .Net Post Api with JavaScript


I've a .net endpoint which returns a jwt token like below enter image description here

I tried to call this endpoint from JavaScript

  const response = await fetch("http://users:6400/api/authenticate/get_token", {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password,
            application_id:'44c5b142-6b05-4d29-98b3-5501ef71db0f',
            web_site:'WakeNC'
        })
    }).then((response) => {             
        if(response.ok) 
        {
            const myJson =  response.json();
             return response.json();               
        }
    }).catch((error) => {             
        console.log(error);
    });

here i'm getting success response, but I'm not able to read the token value i've added the received response value below enter image description here

let me know if anything I've to change, thanks


Solution

  • The Response.json() method returns a Promise. So, you need to await it to get data:

    const response = await fetch("http://users:6400/api/authenticate/get_token", {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password,
            application_id:'44c5b142-6b05-4d29-98b3-5501ef71db0f',
            web_site:'WakeNC'
        })
    }).then(async (response) => {             
        if (response.ok) 
        {
            let myJson = await response.json();
            console.log(myJson);              
        }
    }).catch((error) => {             
        console.log(error);
    });