博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
express react_在30分钟内使用Express.js构建博客并进行React
阅读量:2510 次
发布时间:2019-05-11

本文共 27479 字,大约阅读时间需要 91 分钟。

express react

Building a web server sounds complicated, but it doesn't have to be! What if I told you that you can create a web server with just a couple lines of code? Yes! You can do things like this using Express.js (the most popular web framework for Node developers).

构建Web服务器听起来很复杂,但这不是必须的! 如果我告诉您可以仅用几行代码创建Web服务器该怎么办? 是! 您可以使用Express.js(Node开发人员最流行的Web框架)执行类似的操作。

In this tutorial you'll learn how to create a simple "My Blog" App that allows a user can create, edit, and delete a post. You'll also learn how to add authentication to the app so users have to sign in before being allowed to do any CRUD (create, read, update, delete) actions. The tutorial will use the fabulous for authentication. The back-end will use to power the server, for storing and manipulating data, and for automatically generating REST endpoints and controllers from the Sequelize data models.

在本教程中,您将学习如何创建一个简单的“我的博客”应用程序,该应用程序允许用户创建,编辑和删除帖子。 您还将学习如何向应用程序添加身份验证,以便用户必须先登录才能被允许执行任何CRUD(创建,读取,更新,删除)操作。 本教程将使用神话般的进行身份验证。 后端将使用为服务器供电, 用于存储和处理数据,而将根据Sequelize数据模型自动生成REST端点和控制器。

( )

Before you begin, head over to and create an account, or log in if you’ve already signed up. The Okta service is free, and is what you'll be using to handle the user registration, login, logout, etc. It's an API service for managing user identities.

在开始之前,请转到并创建一个帐户,或者如果已经注册则登录。 Okta服务是免费的,您将使用它来处理用户注册,登录,注销等操作。它是用于管理用户身份的API服务。

Once you've signed up for Okta, follow these steps below to configure it. This will make it easier to implement user authentication later on.:

注册Okta后,请按照以下步骤进行配置。 这将使以后更容易实现用户身份验证。

After you log in, you will see the Org Url in the top right corner of your dashboard, save it somewhere for later use. Click Application on the navigation menu.

登录后,您会在仪表板的右上角看到Org Url ,并将其保存在某处以备后用。 单击导航菜单上的应用程序

  • Click the Add Application button.

    单击添加应用程序按钮。

  • Select Web as the software, click the Next button.

    选择Web作为软件,单击“ 下一步”按钮。

  • Enter the following information, then click the Done button.

    输入以下信息,然后单击“ 完成”按钮。

  • Name: My Blog

    名称 :我的博客

  • Base URIs: http://localhost:3000/

    基本URIhttp://localhost:3000/

  • Login redirect URIs: https://localhost:3000/authorization-code/callback

    登录重定向URIhttps://localhost:3000/authorization-code/callback

You will then be redirected to the general page, scroll down you will see Client ID and Client Secret values, save these somewhere for later use. These are your app's API keys that it will use to securely handle user authentication later on via the .

然后,您将被重定向到常规页面,向下滚动您将看到Client IDClient Secret值,将它们保存在某个地方以备后用。 这些是您应用程序的API密钥,以后将通过将其用于安全地处理用户身份验证。

NOTE: You might be wondering why you haven't written any code and are already using an API service here. The reason is that handling user authentication yourself is actually pretty tricky. There are very few ways to do it correctly, and lots of easy ways to mess up that are non-obvious. Using a free service like Okta to handle this piece of the application will make your project code a lot simpler later on.

注意 :您可能想知道为什么没有编写任何代码并且已经在这里使用API​​服务。 原因是您自己处理用户身份验证实际上很棘手。 正确执行此操作的方法很少,而且很多显而易见的简单方法也可以解决。 使用Okta之类的免费服务来处理这部分应用程序,将使您的项目代码稍后变得更加简单。

The way the Okta service works is by using the OAuth/OpenID Connect protocols behind the scenes to handle all of your user management. Okta handles user registration, login, password reset, multi-factor authentication, and lots of other stuff.

Okta服务的工作方式是通过在后台使用OAuth / OpenID Connect协议来处理所有用户管理。 Okta处理用户注册,登录,密码重置,多因素身份验证以及许多其他工作。

( )

You should have node and npm installed, my Node version is v10.10.0 and npm version is 6.4.1. Create a project folder and basic set up with the following:

您应该已经安装了nodenpm ,我的Node版本是v10.10.0 ,npm版本是6.4.1 。 创建一个项目文件夹并使用以下内容进行基本设置:

mkdir myblogcd myblognpm init

Continue selecting enter to accept all default settings.

继续选择回车以接受所有默认设置。

You should now have this folder structure:

您现在应该具有以下文件夹结构:

myblog└── package.json0 directories, 1 file

Now, add two new files, index.js and .env, to your folder, so your project ends up looking like this:

现在,将两个新文件index.js.env添加到您的文件夹中,这样您的项目最终将如下所示:

myblog├── .env├── index.js└── package.json0 directories, 3 files

Now you can install the required npm modules that are needed for this Express.js app. To do so, run the following commands:

现在,您可以安装此Express.js应用程序所需的必需npm模块。 为此,请运行以下命令:

npm install express@4.16.4 --save

(module needed to start the Express web application)

(启动Express Web应用程序所需的模块)

npm install cors@2.8.5 --save

(module enable Cross-origin resource sharing)

(模块启用跨域资源共享)

npm install body-parser@1.18.3 --save

(module that helps to parse incoming request bodies)

(有助于解析传入的请求正文的模块)

npm install dotenv@6.2.0 --save

(module that will load our .env file into process.env variables)

(将我们的.env文件加载到process.env变量中的模块)

npm install nodemon@1.18.9 --save-dev

(tool that helps automatically restart the application when file changed)

(有助于在文件更改时自动重新启动应用程序的工具)

These two npm modules are for Okta authentication.

这两个npm模块用于Okta身份验证。

npm install @okta/oidc-middleware@1.0.2 express-session@1.15.6 --save

In your .env file, use the Org URL, Client ID, and Client Secret you got from the Okta console to fill in the following and paste it in the file (you got them in the setup credentials steps above):

在您的.env文件中,使用从Okta控制台获得的组织URL,客户端ID和客户端密钥填写以下内容并将其粘贴到文件中(在上述设置凭据步骤中获得了它们):

OKTA_ORG_URL={
yourOktaOrgUrl}OKTA_CLIENT_ID={
yourClientId}OKTA_CLIENT_SECRET={
yourClientSecret}REDIRECT_URL=http://localhost:3000/authorization-code/callbackRANDOM_SECRET_WORD='super secret'

NOTE: The RANDOM_SECRET_WORD setting should be a random string you type out. Just bang on the keyboard for a second to output a long random string, and use that value. This value should never be checked into source control as it is used to manage the integrity of your user sessions. It must be kept private on your web servers and should be extremely hard to guess.

注意RANDOM_SECRET_WORD设置应该是您键入的随机字符串。 只需敲击键盘一秒钟即可输出一个较长的随机字符串,然后使用该值。 永远不要将此值检查到源代码管理中,因为它用于管理用户会话的完整性。 它必须在Web服务器上保持私有状态,并且很难猜测。

In your index.js file, paste in the following code:

index.js文件中,粘贴以下代码:

require('dotenv').config();const express = require('express');const path = require('path');const cors = require('cors');const bodyParser = require('body-parser');const session = require('express-session');const {
ExpressOIDC } = require('@okta/oidc-middleware');const app = express();const port = 3000;// session support is required to use ExpressOIDCapp.use(session({
secret: process.env.RANDOM_SECRET_WORD, resave: true, saveUninitialized: false}));const oidc = new ExpressOIDC({
issuer: `${
process.env.OKTA_ORG_URL}/oauth2/default`, client_id: process.env.OKTA_CLIENT_ID, client_secret: process.env.OKTA_CLIENT_SECRET, redirect_uri: process.env.REDIRECT_URL, scope: 'openid profile', routes: {
callback: {
path: '/authorization-code/callback', defaultRedirect: '/admin' } }});// ExpressOIDC will attach handlers for the /login and /authorization-code/callback routesapp.use(oidc.router);app.use(cors());app.use(bodyParser.json());app.get('/', (req, res) => {
res.send('

Welcome!!

');});app.listen(port, () => console.log(`My Blog App listening on port ${
port}!`))

Let me explain what the above code does. The line that starts with app.use(session…) created session middleware with the options we passed it. This is required for ExpressOIDC's configuration. OIDC stands for OpenID Connect, it is an authentication layer on top of OAuth 2.0. You can learn more about the OpenID Connect & OAuth 2.0 API .

让我解释一下以上代码的作用。 以app.use(session…)开头的行创建了带有我们传递的选项的会话中间件。 这是ExpressOIDC的配置所必需的。 OIDC代表OpenID Connect,它是OAuth 2.0之上的身份验证层。 您可以了解有关OpenID Connect&OAuth 2.0 API的更多 。

The line that starts with const oidc = new ExpressOIDC(...) created an instance of ExpressOIDC with the option we passed in. It enables your application to participate in the by redirecting the user to Okta for authentication and handling the callback from Okta. Once the flow is completed, a local session is created and the user context is saved for the duration of the session.

const oidc = new ExpressOIDC(...)开头的行使用我们传入的选项创建了ExpressOIDC的实例。通过将用户重定向到Okta进行身份验证并处理回调,它使您的应用程序可以参与来自Okta。 流程完成后,将创建本地会话,并在会话持续时间内保存用户上下文。

The app.use(oidc.router) line is required in order for ensureAuthenticated and isAuthenticated to work. It also adds the following route:

必须使用app.use(oidc.router)行,以确保ensureAuthenticatedisAuthenticated正常工作。 它还添加以下路线:

  • /login - redirects to the Okta sign-in page by default

    /login login-默认情况下重定向到Okta登录页面

  • /authorization-code/callback - processes the OIDC response, then attaches user info to the session

    /authorization-code/callback处理OIDC响应,然后将用户信息附加到会话

Now that work is done, you can move on to the next step. In package.json, add "start": "./node_modules/.bin/nodemon index.js" under scripts. This will allow you to simply type npm start to start the application. nodemon is a utility that will monitor for any changes in your source and automatically reload, so you don’t have to restart your server manually.

现在工作已经完成,您可以继续下一步。 在package.json ,在脚本下添加"start": "./node_modules/.bin/nodemon index.js" 。 这将使您只需键入npm start即可启动应用程序。 nodemon是一个实用程序,它将监视源中的任何更改并自动重新加载,因此您不必手动重新启动服务器。

"scripts": {
"start": "nodemon index.js", "test": "echo \"Error: no test specified\" && exit 1" },

Run npm start then go to and you should see:

运行npm start然后转到 ,您应该看到:

Now you have your Express.js app set up! Next you’ll integrate with OpenID Connect (OIDC) to let the user sign in.

现在,您已经设置了Express.js应用程序! 接下来,您将与OpenID Connect(OIDC)集成,以使用户登录。

( )

Because we have added app.use(oidc.router) to our index.js, we got the /login route for free, which means we don't have to set it up ourselves. Anytime a request goes to /login, Okta middleware will take care for us.

因为我们已经将app.use(oidc.router)添加到index.js ,所以我们免费获得了/login路由,这意味着我们不必自己进行设置。 每当有请求发送到/login ,Okta中间件都会为我们服务。

Let's add a link to let user login. In index.js, replace:

让我们添加一个链接以允许用户登录。 在index.js ,替换为:

app.get('/', (req, res) => {
res.send('

Welcome!!

');});

With:

带有:

app.get('/home', (req, res) => {
res.send('

Welcome!!Login');});app.get('/admin', (req, res) =>{
res.send('Admin page');});

Now, when you visit , you should see the login link. Be aware that we added /home after http://localhost:3000.

现在,当您访问 ,您应该会看到登录链接。 请注意,我们在http://localhost:3000之后添加了/home

Click on the login link, you will see the Okta login page. If you log in successfully, you will be redirected back to the URL that you provided to OIDC middleware (the defaultRedirect URL)

单击登录链接,您将看到Okta登录页面。 如果成功登录,您将被重定向回您提供给OIDC中间件的URL(默认重定向URL)。

const oidc = new ExpressOIDC({
issuer: `${
process.env.OKTA_ORG_URL}/oauth2/default`, client_id: process.env.OKTA_CLIENT_ID, client_secret: process.env.OKTA_CLIENT_SECRET, redirect_uri: process.env.REDIRECT_URL, scope: 'openid profile', routes: {
callback: {
path: '/callback', defaultRedirect: '/admin' } }});

In our application set up, we provided /admin as the defaultRedirect URL in the ExpressOIDC setup, so now you should see the admin page.

在我们的应用程序设置中,我们在ExpressOIDC设置中提供了/admin作为defaultRedirect URL,因此现在您应该看到admin页面。

Add oidc.ensureAuthenticated() to the /admin route, so if someone gets the link, he/she still can't see the page without logging in.

oidc.ensureAuthenticated()添加到/admin路由,因此,如果有人获得了链接,则他/她如果没有登录就仍然看不到该页面。

app.get('/admin', oidc.ensureAuthenticated(), (req, res) =>{
res.send('Admin page');})

Add the following routes after get('/admin', …), so the user can log out and when they visit other unexpected pages, we will redirect them back to home page.

get('/admin', …)之后添加以下路由,以便用户可以注销,并且当他们访问其他意外页面时,我们会将其重定向回首页。

app.get('/logout', (req, res) => {
req.logout(); res.redirect('/home');});app.get('/', (req, res) => {
res.redirect('/home');});

You've now got an app built using Express.js and Okta (for OIDC), so let's move on to the next step.

现在,您已经有了一个使用Express.js和Okta(适用于OIDC)构建的应用程序,因此让我们继续下一步。

( )

We are going to use SQLite as our database for storage, and Sequelize as our ORM. We are also going to use Epilogue to generate the REST endpoints. Without Epilogue, you would need to manually setup the POST, GET, PUT, and DELETE API endpoints for blog posts manually.

我们将使用SQLite作为我们的存储数据库,并使用Sequelize作为我们的ORM。 我们还将使用Epilogue生成REST端点。 如果没有Epilogue,则需要手动为博客文章手动设置POST,GET,PUT和DELETE API端点。

Install the following modules:

安装以下模块:

npm install sqlite3@4.0.4 sequelize@4.42.0 epilogue@0.7.1 --save

And then add the following code to the top of your index.js after the require section:

然后将以下代码添加到index.js顶部的require部分之后:

const Sequelize = require('sequelize');const epilogue = require('epilogue'), ForbiddenError = epilogue.Errors.ForbiddenError;

Add the following code to the bottom of your index.js after the routes:

在路由之后,将以下代码添加到index.js的底部:

const database = new Sequelize({
dialect: 'sqlite', storage: './db.sqlite', operatorsAliases: false,});const Post = database.define('posts', {
title: Sequelize.STRING, content: Sequelize.TEXT,});epilogue.initialize({
app, sequelize: database });const PostResource = epilogue.resource({
model: Post, endpoints: ['/posts', '/posts/:id'],});PostResource.all.auth(function (req, res, context) {
return new Promise(function (resolve, reject) {
if (!req.isAuthenticated()) {
res.status(401).send({
message: "Unauthorized" }); resolve(context.stop); } else {
resolve(context.continue); } })});database.sync().then(() => {
oidc.on('ready', () => {
app.listen(port, () => console.log(`My Blog App listening on port ${
port}!`)) });});oidc.on('error', err => {
// An error occurred while setting up OIDC console.log("oidc error: ", err);});

You have just set up the database using Sequelize and created the REST endpoints using Epilogue. I will explain more below.

您刚刚使用Sequelize设置了数据库,并使用Epilogue创建了REST端点。 我将在下面解释更多。

The line that starts with const database = new Sequelize(...) sets up a connection with the SQLite database and tells the database to store the data in ./db.sqlite.

const database = new Sequelize(...)开头的行与SQLite数据库建立了连接,并告诉数据库将数据存储在中。 /db.sqlite

The line that starts with const Post = database.define('posts'...) defines the model which represents a table in the database. We are going to store the title and the context as strings in the database.

const Post = database.define('posts'...)开头的行定义了表示数据库中表的模型。 我们将标题和上下文作为字符串存储在数据库中。

The line epilogue.initialize({ app, sequelize: database }) initializes Epilogue with our Express.js app and the database we just set up.

行Epilogue.initialize epilogue.initialize({ app, sequelize: database })用我们的Express.js应用程序和我们刚刚建立的数据库初始化Epilogue。

The line that starts with const PostResource = epilogue.resource created the REST resource, so now we have the create, list, read, update, and delete controllers with corresponding endpoints for our post.

const PostResource = epilogue.resource开头的行创建了REST资源,因此现在我们具有用于发布的具有相应端点的控制器,创建,列出,读取,更新和删除控制器。

We also added an authentication check to all CRUD routes using the code in PostResource.all.auth section so that all endpoints are protected:

我们还使用PostResource.all.auth部分中的代码向所有CRUD路由添加了身份验证检查,以便保护所有端点:

PostResource.all.auth(function (req, res, context) {
return new Promise(function (resolve, reject) {
if (!req.isAuthenticated()) {
res.status(401).send({
message: "Unauthorized" }); resolve(context.stop); } else {
resolve(context.continue); } })});

By now, your index.js file should look like this:

现在,您的index.js文件应如下所示:

require('dotenv').config();const express = require('express');const path = require('path');const cors = require('cors');const bodyParser = require('body-parser');const session = require('express-session');const {
ExpressOIDC } = require('@okta/oidc-middleware');const Sequelize = require('sequelize');const epilogue = require('epilogue'), ForbiddenError = epilogue.Errors.ForbiddenError;const app = express();const port = 3000;// session support is required to use ExpressOIDCapp.use(session({
secret: process.env.RANDOM_SECRET_WORD, resave: true, saveUninitialized: false}));const oidc = new ExpressOIDC({
issuer: `${
process.env.OKTA_ORG_URL}/oauth2/default`, client_id: process.env.OKTA_CLIENT_ID, client_secret: process.env.OKTA_CLIENT_SECRET, redirect_uri: process.env.REDIRECT_URL, scope: 'openid profile', routes: {
callback: {
path: '/authorization-code/callback', defaultRedirect: '/admin' } }});// ExpressOIDC will attach handlers for the /login and /authorization-code/callback routesapp.use(oidc.router);app.use(cors());app.use(bodyParser.json());app.get('/home', (req, res) => {
res.send('

Welcome!!

Login');});app.get('/admin', oidc.ensureAuthenticated(), (req, res) => {
res.send('Admin page');});app.get('/logout', (req, res) => {
req.logout(); res.redirect('/home');});app.get('/', (req, res) => {
res.redirect('/home');});const database = new Sequelize({
dialect: 'sqlite', storage: './db.sqlite', operatorsAliases: false,});const Post = database.define('posts', {
title: Sequelize.STRING, content: Sequelize.TEXT,});epilogue.initialize({
app, sequelize: database });const PostResource = epilogue.resource({
model: Post, endpoints: ['/posts', '/posts/:id'],});PostResource.all.auth(function (req, res, context) {
return new Promise(function (resolve, reject) {
if (!req.isAuthenticated()) {
res.status(401).send({
message: "Unauthorized" }); resolve(context.stop); } else {
resolve(context.continue); } })});database.sync().then(() => {
oidc.on('ready', () => {
app.listen(port, () => console.log(`My Blog App listening on port ${
port}!`)) });});oidc.on('error', err => {
// An error occurred while setting up OIDC console.log("oidc error: ", err);});

The backend setup is now done, but we still need to build the UI to demonstrate it's working. Let's create the UI using React.

现在已经完成了后端设置,但是我们仍然需要构建UI来演示其工作原理。 让我们使用React创建UI。

( )

If you are going to build a production-ready app, you should ideally install React in your repo, but since our app is for demo purposes, we'll use React via a content delivery network (CDN) instead, to keep things simple.

如果要构建可用于生产环境的应用程序,则理想情况下应该在存储库中安装React,但是由于我们的应用程序是出于演示目的,因此我们将通过内容交付网络(CDN)使用React,以使事情变得简单。

Create a public folder under myblog, then create the files admin.html, admin.js, home.html, home.js in the public folder. Your folder structure should look like this:

myblog下创建一个public文件夹,然后在该公共文件夹中创建文件admin.htmladmin.jshome.htmlhome.js 。 您的文件夹结构应如下所示:

myblog├── .env├── index.js├── package.json└── public    ├── admin.html    ├── admin.js    ├── home.html    └── home.js1 directory, 7 files

Because you are using React, you’ll also use JavaScript to create the UI component. admin.js will contain the React code that we need for the admin page. This page will only be visible to the user after they log in. It will display all the blog posts and allow the user to create new posts, as well as update or delete existing posts. home.js will contain the welcome page and a login button. You are going to embed admin.js in admin.html and home.js in home.html.

因为您使用的是React,所以您还将使用JavaScript创建UI组件。 admin.js将包含管理页面所需的React代码。 该页面仅在用户登录后对用户可见。它将显示所有博客文章,并允许用户创建新文章以及更新或删除现有文章。 home.js将包含欢迎页面和登录按钮。 你要嵌入admin.jsadmin.htmlhome.jshome.html

Paste the following code in home.html. It will load the React JavaScript and bootstrap CSS files for the home page.

将以下代码粘贴到home.html 。 它将为主页加载React JavaScript并引导CSS文件。

   
Home Page

Paste the following code in home.js. It will render the navigation menu with the Login button.

将以下代码粘贴到home.js 。 它将使用“ 登录”按钮呈现导航菜单。

const e = React.createElement;const AppNav = () => (   
);class Home extends React.Component {
constructor(props) {
super(props); } render() {
return (
Please login to see your posts.
); }}const domContainer = document.querySelector('#root');ReactDOM.render(e(Home), domContainer);

Paste the following code in admin.html. This will load the necessary files for React and Bootstrap in the admin page.

将以下代码粘贴到admin.html 。 这将在管理页面中加载React和Bootstrap的必要文件。

   
Admin Page

Paste the following code into admin.js. It will render the navigation menu with the Logout button. It will also render the Add New Post button.

将以下代码粘贴到admin.js 。 它将使用“ 注销”按钮呈现导航菜单。 它还将呈现“ 添加新帖子”按钮。

'use strict';const e = React.createElement;const AppNav = () => (   
);const Card = ({
item, handleSubmit, handleEdit, handleDelete, handleCancel }) => {
const {
title, content, editMode } = item; if (editMode) {
return (
) } else {
return (
{
title || "No Title"}

{

content || "No Content"}

) }}class Admin extends React.Component {
constructor(props) {
super(props); this.state = {
data: [] }; } componentDidMount() {
this.getPosts(); } getPosts = async () => {
const response = await fetch('/posts'); const data = await response.json(); data.forEach(item => item.editMode = false); this.setState({
data }) } addNewPost = () => {
const data = this.state.data; data.unshift({
editMode: true, title: "", content: "" }) this.setState({
data }) } handleCancel = async () => {
await this.getPosts(); } handleEdit = (postId) => {
const data = this.state.data.map((item) => {
if (item.id === postId) {
item.editMode = true; } return item; }); this.setState({
data }); } handleDelete = async (postId) => {
await fetch(`/posts/${
postId}`, {
method: 'DELETE', headers: {
'content-type': 'application/json', accept: 'application/json', }, }); await this.getPosts(); } handleSubmit = async (event) => {
event.preventDefault(); const data = new FormData(event.target); const body = JSON.stringify({
title: data.get('title'), content: data.get('content'), }); const headers = {
'content-type': 'application/json', accept: 'application/json', }; if (data.get('id')) {
await fetch(`/posts/${
data.get('id')}`, {
method: 'PUT', headers, body, }); } else {
await fetch('/posts', {
method: 'POST', headers, body, }); } await this.getPosts(); } render() {
return (
{
this.state.data.length > 0 ? ( this.state.data.map(item =>
) ) : (
You don't have any posts. Use the "Add New Post" button to add some new posts!
) }
); }}const domContainer = document.querySelector('#root');ReactDOM.render(e(Admin), domContainer);

I have attached a handler function to each button. For example, for the Save button, I have attached the handleSubmit function. With this function, when the user clicks the Save button in a card, it checks whether the current card has an ID to tell if it’s a new post or the user is trying to update an existing post. If it’s a new post, it will make a POST API call to the /posts API with the title and the context as POST body. If it’s an existing post, it will make a PUT API call to the /posts/:id API with the updated title and context as PUT body.

我已将处理函数附加到每个按钮。 例如,对于“ 保存”按钮,我已附加了handleSubmit函数。 使用此功能,当用户单击卡片中的“ 保存”按钮时,它将检查当前卡片是否具有ID来标识它是新帖子还是用户正在尝试更新现有帖子。 如果是新帖子,它将以标题和上下文作为POST正文,对/posts API进行POST API调用。 如果是现有帖子,它将使用更新后的标题和上下文作为PUT主体对/posts/:id API进行PUT API调用。

NOTE: It’s important to add a handler function to each button because when the user clicks the button, some actions should be triggered, and you want to execute these actions in the handler function.

注意 :向每个按钮添加处理程序功能很重要,因为当用户单击按钮时,应触发一些操作,并且您想在处理程序功能中执行这些操作。

Now you need to update your index.js file to use admin.html whenever a user visits /admin and use home.html when a user visits /home.

现在,您需要更新index.js文件,以在用户访问/admin时使用admin.html并在用户访问/home时使用home.html

Add this line after the line app.use(bodyParser.json()):

app.use(bodyParser.json())行之后添加以下行:

app.use(express.static(path.join(__dirname, 'public')));

Update the app.get('/home', ...) and app.get('/admin', ...) route to:

app.get('/home', ...)app.get('/admin', ...)路由更新为:

app.get('/home', (req, res) => {
res.sendFile(path.join(__dirname, './public/home.html'));});app.get('/admin', oidc.ensureAuthenticated(), (req, res) => {
res.sendFile(path.join(__dirname, './public/admin.html'));});

Now, if you go to , run npm start and log in, you should able to add new posts, update, and delete existing posts!

现在,如果您转到 ,运行npm start并登录,您应该能够添加新帖子,更新和删除现有帖子!

Woohoo! You have now built a fully functioning single page blog app, connected it to a REST API server, and secured it with authentication via Okta’s ExpressOIDC. You can hopefully see here how easy it is to implement the using Okta’s library.

oo! 现在,您已经构建了一个功能齐全的单页博客应用程序,将其连接到REST API服务器,并通过Okta的ExpressOIDC进行了身份验证来保护它。 您可以希望在这里看到使用Okta的库实现多么容易。

( )

I hope you found this post helpful. If you want to learn more about Node.js, Express.js, or React, there are many great posts on the Okta developer blog. Here are a few to get you started:

希望这篇文章对您有所帮助。 如果您想了解有关Node.js,Express.js或React的更多信息,Okta开发人员博客上有很多不错的文章。 以下是一些入门指南:

Andddddd. If you liked this post, please tweet us and let us know! We love hearing from you! =)

安德 如果您喜欢这篇文章,请在推特上告诉我们! 我们很高兴收到您的来信! =)

翻译自:

express react

转载地址:http://yruwd.baihongyu.com/

你可能感兴趣的文章
HUT-XXXX Strange display 容斥定理,线性规划
查看>>
mac修改用户名
查看>>
一道关于员工与部门查询的SQL笔试题
查看>>
Canvas基础
查看>>
[Hive - LanguageManual] Alter Table/Partition/Column
查看>>
可持久化数组
查看>>
去除IDEA报黄色/灰色的重复代码的下划波浪线
查看>>
Linux发送qq、网易邮件服务配置
查看>>
几道面试题
查看>>
【转】使用 WebGL 进行 3D 开发,第 1 部分: WebGL 简介
查看>>
js用正则表达式控制价格输入
查看>>
chromium浏览器开发系列第三篇:chromium源码目录结构
查看>>
java开发操作系统内核:由实模式进入保护模式之32位寻址
查看>>
第五讲:单例模式
查看>>
Python编程语言的起源
查看>>
Azure ARMTemplate模板,VM扩展命令
查看>>
使用Masstransit开发基于消息传递的分布式应用
查看>>
[CF808A] Lucky Year(规律)
查看>>
关于推送遇到的一些问题
查看>>
寒假作业3 抓老鼠啊~亏了还是赚了?
查看>>