📅  最后修改于: 2023-12-03 15:35:09.905000             🧑  作者: Mango
Strapi是一个基于Node.js的开源CMS框架,它提供了RESTful API接口,可以在自己的应用程序中调用。本文将介绍如何使用Javascript编写Strapi的登录API。
在编写代码之前,我们需要搭建好Strapi的环境,并创建好一个用户。具体步骤可以参考官方文档 Getting Started with Strapi。
在本地项目中安装 node-fetch
,我们将使用它来进行HTTP请求。
npm install node-fetch
使用下面的代码来构建URL:
const url = "http://localhost:1337/auth/local";
我们需要准备好POST数据,包括用户名和密码。可以通过Prompt弹出框,让用户在浏览器中输入用户名和密码。下面是一个例子:
const email = window.prompt("Email address:");
const password = window.prompt("Password:");
使用 node-fetch
发起请求,并将响应转换为JSON格式对象。
const data = { identifier: email, password };
const options = {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
};
const response = await fetch(url, options);
const result = await response.json();
如果请求成功,result
对象将包含JWT Token。我们可以将其存储在本地存储中,并重定向到我们的应用程序。
if (response.status === 200) {
localStorage.setItem("jwt", result.jwt);
window.location.href = "/dashboard";
} else {
// 处理登录失败的情况
console.error(result);
}
下面是完整的Javascript代码:
const url = "http://localhost:1337/auth/local";
const email = window.prompt("Email address:");
const password = window.prompt("Password:");
const data = { identifier: email, password };
const options = {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
};
const response = await fetch(url, options);
const result = await response.json();
if (response.status === 200) {
localStorage.setItem("jwt", result.jwt);
window.location.href = "/dashboard";
} else {
// 处理登录失败的情况
console.error(result);
}
在本文中我们了解了如何使用Javascript编写Strapi的登录API。虽然示例代码相对简单,但是你可以通过学习这个例子来开发更复杂的应用程序。