大佬教程收集整理的这篇文章主要介绍了使用 Typescript / Javascript 中的 URL 登录名和密码连接到 API,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 Web 编程的新手,如果我拥有的唯一信息是 URL、使用纯 Typescript 或 JavaScript 的登录名和密码,我想知道如何轻松请求连接到 API。 目标是检索访问令牌。
我建议使用使用 promise 的浏览器获取 API。
让我们从这里开始。过去的浏览器提供 AJAX 调用,但自从现代 JS 通过 promise 实现之后,一切都变得非常简单。您可以了解有关 promises
here 的更多信息。
让我们考虑一个与您的情况类似的示例,其中您有一个 url
端点,以及您想要发送到 url
的一些数据。我们期望 url
以包含 JSON
的 token
负载响应。
// so we will define our constants here
const url = 'http://localhost/login';
const username = 'username';
const password = 'password';
// now we configure the fetch request to the url endpoint.
// we should probably put it inside a separate function since
// you're using a browser,you probably will bind this request
// to a click event or something.
function login() {
return fetch(url,{
// in the case of a login request most APIs use the POST method offered by
// RESTful APIs
method: 'post',// can be 'get','put','delete',and many more
// now we set any needed headers specified by the API
headers: {
// most APIs I have worked with use
'Content-Type': 'application/json',// but some might need more,they will specify anyway.
},// because we are using the 'post' method then we will need to add
// a body to the request with all our data,body excepts a String so
// we do the following
body: JSON.Stringify({
username: username,password: password,}),})
// Now we handle the response because the function returns a promise
.then((responsE) => {
// An important thing to note is that an error response will not throw
// an error so if the result is not okay we should throw the error
if(!response.ok) {
throw response;
}
// since we expect a json response we will return a json call
return response.json();
})
}
// will define a self calling arrow function that will do the event binding
((button) => {
button.addEventListener('click',(event) => {
// we then call the function here.
login()
.then((responsE) => {
// side note,you could destructure the response argument as { token }
// then just reference token instead.
// recall that we expect this function to have a 'token' key in
// the response payload...so let us log it just to make sure
console.log(result.token);
})
});
// we add the button reference as the argument
})(document.querySELEctor('#submit'));
参考文献:
Promises
RESTful
我希望这有助于更好地了解您的任务,祝您好运
,你可以将 axios 用于 js/ts 像这个例子:
getToken = () => {
axios.post('http://localhost/login',{
username: username,}).then((responsE) => {
let data = response.data;
//do whatever u want here eg :set token to local storage
localStorage.set('token',data.token);
}).catch((error) => {
console.log(error);
});
};
getToken();
以上是大佬教程为你收集整理的使用 Typescript / Javascript 中的 URL 登录名和密码连接到 API全部内容,希望文章能够帮你解决使用 Typescript / Javascript 中的 URL 登录名和密码连接到 API所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。