如何使用JavaScript调用.Net Post API

zte4gxcn  于 2023-03-20  发布在  .NET
关注(0)|答案(2)|浏览(128)

我有一个.net端点,它返回一个jwt标记,如下

所示
我尝试从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);
    });

在这里,我得到了成功响应,但无法读取令牌值,我已将收到的响应值添加到

下方
如果我有什么要改的请告诉我,谢谢

lrpiutwd

lrpiutwd1#

Response.json()方法返回一个Promise,因此,需要等待它获取数据:

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

pjngdqdw2#

在这里,我得到了成功响应,但我无法读取令牌值,我已在下面添加了接收到的响应值
我在你的response.json();中发现了这个问题,它不包含令牌,因为它不是异步的,执行失败了。相反,你应该从const result = await response.text();中读取令牌。另一个重要的问题是,如果你有response viewModel,你应该从模型属性中读取响应,如下所示:

[AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Authenticate([FromBody] LoginViewModel loginInfo)
        {
            IActionResult response = Unauthorized();

            var user = await _authenticationService.AuthenticateLogin(loginInfo);

            if (user.Token != null)
            {
                response = Ok(new ResponseViewModel { output = "success", msg = "Login Successfully", apiResponse = user });
            }

            return response;
        }

但如果您的API只返回令牌,您可以直接获取该令牌作为响应,如下所示:

response = Ok(user.Token);

我们来看看练习:

const response = await fetch("http://localhost:5094/api/Authenticate", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },

                body: JSON.stringify({
                    username: username,
                    password: password,
                    application_id:'44c5b142-6b05-4d29-98b3-5501ef71db0f',
                    web_site:'WakeNC'
                   
                })
            });
            console.log("Rquest Submitted");
            if (!response.ok) {
                throw new Error(response.statusText);
            }

            const result = await response.text();

输出:

**注:**从我的调查中得到一些方法,请尝试等待回应。text();

相关问题