给后端开发者看的实用浏览器API技能

<br>

location

浏览器地址操作对象

  • 路由重定向至新的URL
location.href = "/page"
  • 刷新当前页面
location.reload(/*刷新*/)
  • 如果把 reload(true) 方法的参数设置为 true,那么无论文档的最后修改日期是什么,它都会绕过缓存,从服务器上重新下载该文档。这与用户在单击浏览器的刷新按钮时按住 Shift 健的效果是完全一样

<br>

localStorage

什么是 LocalStoages

  1. 是对 Cookie 的优化
  2. 永久本地存储
  3. 在隐私模式下不可读取
  4. 在所有同源窗口中都是共享的
  5. 不能被爬虫爬取,不要用它完全取代URL传参

关键性的操作

key操作
设置键值localStorage.setItem("key", JSON.stringify(data))
获取键值localStorage.getItem("key")
清楚键值localStorage.removeItem("key")
清楚所有键值localStorage.clear()

<br>

Fetch

用于前后端异步数据交互

// 使用方法
fetch("url", {
    method: "POST",                 // 请求类型(GET, POST, PUT, DELETE, ...)
    headers: {                      // 请求头,含数据类型及 Token
        "Content-Type": "application/json"
    },
    body: JSON.stringify({}),       // 向服务器发送的数据
})
    .then(res => {
        if (res.status === 200) { } // 服务器返回200状态码及处理
        return res.json()
    })
    .then(data => { })              // 服务器返回的数据
    .catch(err => { })              // 错误处理
  • 无注释代码(方便复制)
fetch("url", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({}),
})
    .then(res => {
        if (res.status === 200) { }
        return res.json()
    })
    .then(data => { })
    .catch(err => { })

<br>

Fetch 使用场景模拟

  • 适用于单页WEB客户端
  1. 用户登录
// 登录
fetch("/api/user/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
        Usermail: "你的帐号",
        Password: "你的密码",
    }),
})
    .then(res => {
        // 返回 200 则重新加载页面触发权限认证请求
        if (res.status === 200) { location.reload(/*刷新*/) }
        return res.json()
    })
    .then(data => {
        // 登录成功后将 token 存入 localStorage
        localStorage.setItem("token", JSON.stringify(data))
    })
    .catch(err => { error("登录请求失败") })
  1. 权限认证请求
// 认证请求(页面加载时执行)
fetch("/api/user", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + JSON.parse(localStorage.getItem("token"))
        // 请求头中携带 token 请求服务器认证
    },
})
    .then(res => {
        // 返回 200 则对用户状态进行处理
        // 否则用户将没有权限访问当前页面(做跳转首页处理)
        if (res.status === 200) { this.user_status = true } else {
            this.user_status = false
            location.href = "/"
        }
        return res.json()
    })
    .then(data => { })
    .catch(err => { info("服务器繁忙") })

<br>

不定期更新!!

转载于:https://my.oschina.net/upcyan/blog/1501668

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值