uni-app 实现简单登录注册demo
preface: 用uni-app实现app前端界面,后端使用asp.netwebapi框架实现提供后台api服务。一.所需掌握技术点:1.前端1.网络请求 uni.request2.页面跳转,页面传参 uni.navigateTo3.本地缓存 uni.setStorageSync, uni.getStorageSync2.后端1.Restful 接口设计规范2.http协议 常用方法3.http
·
preface: 用uni-app实现app前端界面,后端使用asp.net webapi控制器实现提供后台api服务。
一.所需掌握技术点:
1.前端
1.网络请求 uni.request
2.页面跳转,页面传参 uni.navigateTo
3.本地缓存 uni.setStorageSync, uni.getStorageSync
2.后端
1.Restful 接口设计规范
2.http协议 常用方法
3.http 状态码(Http Status Code)
4.webapi 控制器设计
后台mssql数据库:
一.用户注册
前端代码:
methods: {
btnReg(){
uni.request({
url: 'https://localhost:44358/api/users',
method: 'POST',
data: {UserName:this.account, Password:this.password, E_Mail:this.email},
success: res => {
uni.showToast({
title:"注册成功",
duration:2000,
success() {
setTimeout(function () {
uni.navigateTo({
url: '../login/login',
});
}, 1000);
}
});
},
fail: () => {},
complete: () => {
}
});
}
}
后端代码:
// POST: api/Users
[ResponseType(typeof(User))]
public async Task<IHttpActionResult> PostUser(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Users.Add(user);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = user.Id }, user);
}
二.用户登录
前端请求代码:
methods: {
bindLogin() {
const data = {
account: this.account,
password: this.password
};
console.log(data);
uni.request({
url: 'https://localhost:44358/api/users',
method: 'GET',
data: {username : this.account, password : this.password},
success: res => {
if(res.statusCode == 404){
uni.showToast({
icon: 'none',
title: '密码或用户名错误',
});
return;
}
console.log(res);
uni.showToast({
icon: 'none',
title: '登录成功',
});
uni.setStorage({
key: 'username',
data: this.account,
success:function(){
console.log("存储用户名到本地成功!");
}
})
uni.reLaunch({
url:'../main/main',
})
},
fail: () => {
},
complete: () => {}
});
}
}
后端接收请求方法:
[ResponseType(typeof(User))]
public async Task<IHttpActionResult> GetUser(string username, string password)
{
User user = await db.Users.FirstOrDefaultAsync(c => c.UserName == username && c.Password == password);
if (user == null)
return NotFound();
return Ok(user);
}
运行过程中的问题:
1.调试遇到的跨域问题.
在web.config中删除 <system.webServer> 节点下的
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
删除后,再添加
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type,Accept" />
</customHeaders>
</httpProtocol>
到web.config 文件中。即可解决跨域请求 HTTP状态码403的问题。
更多推荐
已为社区贡献2条内容
所有评论(0)