目录

介绍

先决条件

代码

创建数据库和表

创建一个Web API项目

创建React项目


介绍

在本文中,我们将逐步学习使用Reactjs和Web API创建用户注册和登录页面的过程。React是一个开放源代码的JavaScript库,用于创建用户界面,尤其是用于单页应用程序的用户界面。它用于控制Web和移动应用程序的视图层。React由Facebook的软件工程师Jordan Walke开发,并由Facebook维护。

先决条件

  1. React.js和Web API的基础知识
  2. Visual Studio
  3. Visual Studio Code
  4. SQL Server Management Studio
  5. Node.js

代码

创建数据库和表

打开SQL Server Management Studio,创建一个名为的Employees数据库,然后在该数据库中创建一个表。该表命名为EmployeeLogin。

CREATE TABLE [dbo].[EmployeeLogin]([Id] [int] IDENTITY(1,1) NOT NULL,[Email] [varchar](50) NULL,[Password] [varchar](50) NULL,[EmployeeName] [varchar](50) NULL,[City] [varchar](50) NULL,[Department] [varchar](50) NULL,CONSTRAINT [PK_EmployeeLogin] PRIMARY KEY CLUSTERED
([Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, _IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]GO

创建一个Web API项目

打开Visual Studio并创建一个新项目。

将名称更改为LoginApplication,然后单击确定 > 选择Web API作为其模板。

在解决方案资源管理器中右键单击Models文件夹,然后转到Add >> New Item >> data

单击“ADO.NET实体数据模型”选项,然后单击“添加”。从数据库中选择EF设计器,然后单击“下一步”按钮。

添加连接属性,然后在下一页上选择数据库名称,然后单击“确定

检查Table checkbox。默认情况下将选择内部选项。现在,单击“完成”按钮。

现在,我们的数据模型已成功创建。

现在添加一个名为VM的新文件夹。右键单击VM文件夹,添加两个三个类,分别是Login,Register和Response。现在,将以下代码粘贴到这些类中。

Login 类:

public class Login{public string Email { get; set; }public string Password { get; set; }}

Register和Response类:

public class Register{public int Id { get; set; }public string Email { get; set; }public string Password { get; set; }public string EmployeeName { get; set; }public string City { get; set; }public string Department { get; set; }}
public class Response
{public string Status { set; get; }public string Message { set; get; }
}

右键单击Controllers文件夹,然后添加一个新的控制器。将其命名为“Login controller”并添加以下名称空间。

using LoginApplication.Models;
using LoginApplication.VM;

在此控制器中创建两个方法以进行插入和登录,然后在该控制器中添加以下代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LoginApplication.Models;
using LoginApplication.VM;namespace LoginApplication.Controllers
{[RoutePrefix("Api/login")]public class LoginController : ApiController{EmployeesEntities DB = new EmployeesEntities();[Route("InsertEmployee")][HttpPost]public object InsertEmployee(Register Reg){try{EmployeeLogin EL = new EmployeeLogin();if (EL.Id == 0){EL.EmployeeName = Reg.EmployeeName;EL.City = Reg.City;EL.Email = Reg.Email;EL.Password = Reg.Password;EL.Department = Reg.Department;DB.EmployeeLogins.Add(EL);DB.SaveChanges();return new Response{ Status = "Success", Message = "Record SuccessFully Saved." };}}catch (Exception){throw;}return new Response{ Status = "Error", Message = "Invalid Data." };}[Route("Login")][HttpPost]public Response employeeLogin(Login login){var log = DB.EmployeeLogins.Where(x => x.Email.Equals(login.Email) && x.Password.Equals(login.Password)).FirstOrDefault();if (log == null){return new Response { Status = "Invalid", Message = "Invalid User." };}elsereturn new Response { Status = "Success", Message = "Login Successfully" };}}
}

现在,让我们启用Cors。转到工具,打开NuGet软件包管理器,搜索Cors,然后安装“Microsoft.Asp.Net.WebApi.Cors”软件包。打开Webapiconfig.cs并添加以下行:

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

创建React项目

现在,使用以下命令创建一个新的reactjs项目:

npx create-reatc-app loginapp

在Visual Studio代码中打开新创建的项目,并使用以下命令在此项目中安装reactstrap和bootstrap:

npm install --save bootstrap
npm install --save reactstrap react react-dom

使用以下命令在React中添加路由:

npm install react-router-dom --save

现在转到src文件夹并添加三个新组件:

  1. Login.js
  2. Reg.js
  3. Dashboard.js

现在打开Reg.js文件并添加以下代码:

import React, { Component } from 'react';
import { Button, Card, CardFooter, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
class Reg extends Component {constructor() {super();this.state = {EmployeeName: '',City: '',Email: '',Password: '',Department: ''}this.Email = this.Email.bind(this);this.Password = this.Password.bind(this);this.EmployeeName = this.EmployeeName.bind(this);this.Password = this.Password.bind(this);this.Department = this.Department.bind(this);this.City = this.City.bind(this);this.register = this.register.bind(this);}Email(event) {this.setState({ Email: event.target.value })}Department(event) {this.setState({ Department: event.target.value })}Password(event) {this.setState({ Password: event.target.value })}City(event) {this.setState({ City: event.target.value })}EmployeeName(event) {this.setState({ EmployeeName: event.target.value })}register(event) {fetch('http://localhost:51282/Api/login/InsertEmployee', {method: 'post',headers: {'Accept': 'application/json','Content-Type': 'application/json'},body: JSON.stringify({EmployeeName: this.state.EmployeeName,Password: this.state.Password,Email: this.state.Email,City: this.state.City,Department: this.state.Department})}).then((Response) => Response.json()).then((Result) => {if (Result.Status == 'Success')this.props.history.push("/Dashboard");elsealert('Sorrrrrry !!!! Un-authenticated User !!!!!')})}render() {return (<div className="app flex-row align-items-center"><Container><Row className="justify-content-center"><Col md="9" lg="7" xl="6"><Card className="mx-4"><CardBody className="p-4"><Form><div class="row" className="mb-2 pageheading"><div class="col-sm-12 btn btn-primary">Sign Up</div></div><InputGroup className="mb-3"><Input type="text"  onChange={this.EmployeeName} placeholder="Enter Employee Name" /></InputGroup><InputGroup className="mb-3"><Input type="text"  onChange={this.Email} placeholder="Enter Email" /></InputGroup><InputGroup className="mb-3"><Input type="password"  onChange={this.Password} placeholder="Enter Password" /></InputGroup><InputGroup className="mb-4"><Input type="text"  onChange={this.City} placeholder="Enter City" /></InputGroup><InputGroup className="mb-4"><Input type="text"  onChange={this.Department} placeholder="Enter Department" /></InputGroup><Button  onClick={this.register}  color="success" block>Create Account</Button></Form></CardBody></Card></Col></Row></Container></div>);}
}export default Reg;<container> <row classname="justify-content-center">
<card classname="mx-4"> <cardbody classname="p-4">

现在,打开Login.js文件,并添加以下代码:

import React, { Component } from 'react';
import './App.css';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
class Login extends Component {constructor() {super();this.state = {Email: '',Password: ''}this.Password = this.Password.bind(this);this.Email = this.Email.bind(this);this.login = this.login.bind(this);}Email(event) {this.setState({ Email: event.target.value })}Password(event) {this.setState({ Password: event.target.value })}login(event) {debugger;fetch('http://localhost:51282/Api/login/Login', {method: 'post',headers: {'Accept': 'application/json','Content-Type': 'application/json'},body: JSON.stringify({Email: this.state.Email,Password: this.state.Password})}).then((Response) => Response.json()).then((result) => {console.log(result);if (result.Status == 'Invalid')alert('Invalid User');elsethis.props.history.push("/Dashboard");})}render() {return (<div className="app flex-row align-items-center"><Container><Row className="justify-content-center"><Col md="9" lg="7" xl="6"><CardGroup><Card className="p-2"><CardBody><Form><div class="row" className="mb-2 pageheading"><div class="col-sm-12 btn btn-primary">Login</div></div><InputGroup className="mb-3"><Input type="text" onChange={this.Email} placeholder="Enter Email" /></InputGroup><InputGroup className="mb-4"><Input type="password" onChange={this.Password} placeholder="Enter Password" /></InputGroup><Button onClick={this.login} color="success" block>Login</Button></Form></CardBody></Card></CardGroup></Col></Row></Container></div>);}
}export default Login;

打开Dashboard.js文件,并添加以下代码:

import React, { Component } from 'react';
import './App.css';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';class Dashboard extends Component {render() {return (<div class="row" className="mb-2 pageheading"><div class="col-sm-12 btn btn-primary">Dashboard </div></div>);}
}export default Dashboard;

打开App.css文件,并添加以下CSS类:

text-align: center;
}
.navheader{      margin-top: 10px;      color :black !important;      background-color: #b3beca!important
}    .PageHeading
{      margin-top: 10px;      margin-bottom: 10px;      color :black !important;
}

打开App.js文件,并添加以下代码:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Login from './Login';
import Reg from './Reg';
import Dashboard from './Dashboard';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
function App() {  return (  <Router>    <div className="container">    <nav className="navbar navbar-expand-lg navheader">    <div className="collapse navbar-collapse" >    <ul className="navbar-nav mr-auto">    <li className="nav-item">    <Link to={'/Login'} className="nav-link">Login</Link>    </li>    <li className="nav-item">    <Link to={'/Signup'} className="nav-link">Sign Up</Link>    </li>      </ul>    </div>    </nav> <br />    <Switch>    <Route exact path='/Login' component={Login} />    <Route path='/Signup' component={Reg} />    </Switch>    <Switch>  <Route path='/Dashboard' component={Dashboard} />    </Switch>  </div>    </Router>   );
}  export default App;

现在,使用npm start命令运行项目,并检查结果。

检查结果

输入详细信息,然后单击按钮。

输入详细资料

输入电子邮件和密码,然后单击登录按钮。

使用Web API和React创建用户注册和登录相关推荐

  1. Web API 2 入门——创建ASP.NET Web API的帮助页面(谷歌翻译)

    在这篇文章中 创建API帮助页面 将帮助页面添加到现有项目 添加API文档 在敞篷下 下一步 作者:Mike Wasson 创建Web API时,创建帮助页面通常很有用,以便其他开发人员知道如何调用A ...

  2. Web APi之控制器创建过程及原理解析(八)

    前言 中秋歇了歇,途中也时不时去看看有关创建控制器的原理以及解析,时间拖得比较长,实在是有点心有余而力不足,但又想着既然诺下了要写完原理一系列,还需有始有终.废话少说,直入主题. HttpContro ...

  3. 使用Entity Framework Core,Swagger和Postman创建ASP.NET Core Web API的分步指南

    目录 介绍 背景 第1步:创建一个新项目 第2步:添加模型类 第3步:使用Entity Framework Core 第4步:添加数据库上下文和控制器 步骤5:在Package Manager控制台中 ...

  4. 使用 Swagger UI 与 Swashbuckle 创建 RESTful Web API 帮助文件

    作者:Sreekanth Mothukuru 2016年2月18日 本文旨在介绍如何使用常用的 Swagger 和 Swashbuckle 框架创建描述 Restful API 的交互界面,并为 AP ...

  5. 【Web API系列教程】1.3 — 实战:用ASP.NET Web API和Angular.js创建单页面应用程序(上)

    前言 在传统的web应用程序中,客户端(浏览器)通过请求页面来启动与服务器的通信.然后服务器处理该请求,并发送HTML页面到客户端.在随后页面上的操作中--例如,用户导航到一个链接或提交一个包含数据的 ...

  6. Asp.Net Web API 2第一课——入门

    前言 Http不仅仅服务于Web Pages.它也是一个创建展示服务和数据的API的强大平台.Http是简单的.灵活的.无处不在的.你能想象到几乎任何的平台都会有HTTP服务库.HTTP服务可以涉及到 ...

  7. 返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API

    返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API 原文:返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 ...

  8. ASP.NET Web API 基本操作(CRUD)

    上一篇介绍了ASP.NET Web API的基本知识和原理,这一篇我们通过一个更直观的实例,对产品进行CRUD操作(Create/Read/Update/Delete)来继续了解一下它的基本应用. 创 ...

  9. java调用asp.net webapi_通过HttpClient 调用ASP.NET Web API示例

    在前面两篇文章中我们介绍了ASP.NET Web API的基本知识和原理,并且通过简单的实例了解了它的基本(CRUD)操作.我们是通过JQuery和Ajax对Web API进行数据操作.这一篇我们来介 ...

最新文章

  1. 如何评判软件测试培训机构的好坏?
  2. PostgreSql 功能和操作
  3. bugzilla dbd-mysql_Linux下安装Bugzilla——完整版
  4. PL/SQL developer执行的sql文件编码
  5. 【干货】救火必备:线上故障排查套路大全
  6. 设计模式(十)——抽象工厂模式
  7. LiveVideoStack成立5周年生日快乐!一路走来,感谢有你!
  8. 一种User Mode下访问物理内存及Kernel Space的简单实现
  9. Intellij IDEA中分屏显示方法
  10. c语言-命令行选项_EWSTM8系列教程06_工程节点选项配置(一)
  11. nutz配置druid监控
  12. 根据实例详解Java中的反射机制
  13. 小米商城抢购脚本_小米十周年感恩季-816活动攻略
  14. VUE Error:if there's nested data,rowKey is required错误
  15. 在OpenCV中使用YOLO v3进行物体检测
  16. 从阿里的产品能力模型分析,转产品如何避免“从头开始”
  17. KMP --算法竞赛(33)
  18. Django+itchat+apscheduler实现向指定微信群和微信好友定时发送信息和文件
  19. 多租户 Saas 系统架构的设计思路
  20. 与病毒名称相似,“捏脸”游戏 ZEPETO 涉嫌窃听?...

热门文章

  1. python粒子风暴代码_turtle爆炸粒子效果源码
  2. java mongo忽略大小写_Java Spring Mongo排序忽略大小写问题
  3. android+5+镜像,1 下载AOSP(Android)镜像
  4. 潮流海报模板|2021渐变流体必备
  5. 2.5D休闲娱乐生活类插画素材,给设计添彩!
  6. 设计素材导航网站,宝藏都在里面!
  7. gc:C语言的垃圾回收库-英文
  8. Linux内核之XArray
  9. mysql根据时间回退_MySQL 中的日期时间类型
  10. pcre安装_Nginx | Nginx的介绍和安装