封装api(登录页面)

  • 在项目开发过程中,为了方便统一操作,通常会把API封装到一个文件里,在页面直接使用就可以了,避免后端修改接口的时候在每一个发请求的页面修改。
  • 鉴于这个项目对API的封装不同于以往的做法,我决定记录自己封装的每一个API。
  • 获取后端图形验证API封装:

const HOST = "http://192.168.0.135";//接口路径
const CAPRCHA = HOST + "/captcha.jpg";//验证码路径

export function getCaptcha(successFn) {
    axios.get(CAPRCHA)
        .then(function(res) {
            if (res.status == 200) {
                var imgUrl = res.config.url
                successFn(imgUrl);//将验证码的路径用函数返回
            }
        })
        .catch(function(error) {
            console.log(error);
        });
}
//将获取验证码API导出
export default {
    getCaptcha: getCaptcha
}

/*在登录页面使用 ,在vue实例被创建的时候发请求,获取图形验证码*/
import { getCaptcha, getUserInfo} from "@/api/index.js";//在登录页面引入

  mounted() {
  //在mounted函数中调用
    const _this = this;
    getCaptcha(_this.showImg);
  },
  • 封装登录API
//登录,向后端传参,发post请求

export function getUserInfo(data,successFn) {
  axios.post(LOGIN + "?t=" + new Date().getTime(), data)
      .then(function(response) {
          console.log(response);
          if (response.data.code == 500) {
              getCaptcha()
          }
          if(response.data.code==200){
  				successFn()//登录成功执行的方法
  		}
      })
      .catch(function(error) {
          console.log(error);
      });
}
const LOGIN = HOST + "/login";//定义登录请求的路径
//在登录页面使用
login() {
    var data={loginName:this.form.username,  loginPassword:this.form.password,captcha:this.form.code
    }
      getUserInfo(data,this.toIndex)//获取用户的用户名和密码,传给后端。
,toIndex(){
//登录成功跳转页面
  	this.$router.push("/index");
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastAPI 的 cookies 是使用 Python 的 `http.cookies` 模块来处理的。要实现 cookies 保持登录的功能,需要将用户的身份信息存储在 cookies 中,并在每个请求中读取 cookies 中的信息来验证用户身份。 以下是一个使用 FastAPI 实现 cookies 保持登录的示例: ```python from fastapi import FastAPI, Request, Response from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from http import cookies app = FastAPI() templates = Jinja2Templates(directory="templates") # 假设这是一个数据库,存储了用户的身份信息 users_db = { "alice": "password1", "bob": "password2", } # 登录页面 @app.get("/") async def login_form(request: Request): return templates.TemplateResponse("login.html", {"request": request}) # 处理登录请求 @app.post("/login") async def login(request: Request, response: Response, username: str, password: str): # 验证用户身份信息 if username in users_db and users_db[username] == password: # 将用户信息存储在 cookies 中 c = cookies.SimpleCookie() c["username"] = username c["username"]["max-age"] = 3600 response.headers["Set-Cookie"] = c.output(header='') # 登录成功,跳转到受保护的页面 return templates.TemplateResponse("protected.html", {"request": request, "username": username}) else: # 登录失败,返回错误信息 return templates.TemplateResponse("login.html", {"request": request, "error": "Invalid username or password"}) # 受保护的页面,只有登录后才能访问 @app.get("/protected", response_class=HTMLResponse) async def protected(request: Request): # 从 cookies 中读取用户信息 username = request.cookies.get("username") if not username: # 用户未登录,跳转到登录页面 return templates.TemplateResponse("login.html", {"request": request}) else: # 用户已登录,显示受保护的页面 return templates.TemplateResponse("protected.html", {"request": request, "username": username}) ``` 在上面的代码中,首先定义了一个 `users_db` 字典,用于存储用户的身份信息。登录页面使用 `login.html` 模板,显示登录表单;处理登录请求的函数使用 `post` 方法,验证用户身份信息,并将用户信息存储在 cookies 中;受保护的页面使用 `protected.html` 模板,只有登录后才能访问。 在处理登录请求时,使用 `http.cookies` 模块创建一个 `SimpleCookie` 对象,将用户名存储在 cookies 中,并设置了 `max-age` 属性为 3600 秒,表示 cookies 会在 1 小时后过期。然后将 cookies 添加到响应头中,以便浏览器可以将 cookies 保存到本地。 在受保护的页面中,使用 `request.cookies.get("username")` 方法从 cookies 中读取用户名,如果不存在,则表示用户未登录,跳转到登录页面;如果存在,则表示用户已登录,显示受保护的页面

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值