|
Post by account_disabled on Jan 27, 2024 18:49:35 GMT 14
在本教程中,我们将在Node.js Web 应用程序中通过 Facebook 和 GitHub 实现身份验证。为此,我们将使用Passport,它是 Node.js 的身份验证中间件。Passport 支持使用提供商进行身份验证。 快速网络应用程序 开始之前,请确保您的计算机上安装了 Node.js。 我们将首先为我们的应用程序创建文件夹,然后在终端上访问该文件夹: mkdir AuthApp cd AuthApp 要创建节点应用程序,我们将使用以下命令: Learn to Code with JavaScript npm init 系统将提示您提供 Node 的一些信息package.json。只需点击enter直到最后即可保留默认配置。 接下来,我们需要一个 HTML 文件发送给客户端。在应用程序的根文件夹中创建一个名为的文件auth.html,其中包含以下内容这就是本教程所需的全部 HTML。 您还需要Express,这是一个受 Ruby 的 Sinatra 启发的用于构建 Web 应用程序的框架。 要安装 Express,请从终端键入以下命令 完成此操作后,就可以编写一些代码了。 在应用程序的根文件夹中创建一个文件index.js,并向其中添加以下内容 在上面的代码中,我们需要 Express 并通过调用express()创建我们的 Express 应用程序。然后我们声明应用 WhatsApp 号码数据 程序主页的路由。在那里,我们将创建的 HTML 文件发送到访问该路由的客户端。然后,我们将process.env.PORT端口设置为环境端口变量(如果存在)。否则,我们将默认为3000,这是我们将在本地使用的端口。这为您提供了足够的灵活性,可以从开发直接切换到生产环境,其中端口可能由服务提供商(例如Heroku)设置。在下面,我们使用我们设置的端口变量调用app.listen(),并通过一个简单的日志让我们知道一切正常,以及应用程序正在侦听哪个端口。 现在我们应该启动我们的应用程序以确保一切正常工作。 只需在终端上编写以下命令: node index.js 您应该看到消息:App listening on port 3000。如果情况并非如此,您可能错过了一步。返回并再试一次。 继续,让我们看看我们的页面是否正在向客户端提供服务。转到您的网络浏览器并导航至。 如果您可以看到我们在 中创建的页面auth.html,那么我们就可以开始了。 返回终端并使用ctrl+停止应用程序c。所以记住,当我说启动应用程序时,你写node index.js,当我说停止应用程序时,你写。清除?很好,你刚刚被编程了 设置护照 您很快就会意识到,Passport 使我们可以轻松地为用户提供身份验证。让我们使用以下命令安装 在这里,我们需要 Passport 并直接在 Express 应用程序中初始化它及其会话身份验证中间件。然后,我们设置' success'和' error'路由,这将呈现一条消息,告诉我们身份验证是如何进行的。
|
|