账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    fetch请求怎么加入session?
    19
    0

    项目用的是fetch做的请求,后台说可以用session来处理会话权限!但是请求头中怎么加入session。

    查了查资料说是request.getSession 可以获取到,但是在fetch封装的请求中找不到request,有些疑惑?应该怎么封装。。。

    export const get = (url, query = {}, options = {}) => {
      const defaultOpt = {
        method: 'GET',
        timeout: requestTimeOut,
        credentials: 'include',
        headers: { ...options }
      }
    
      defaultOpt.headers = completeHeader(defaultOpt.headers)
      console.log(defaultOpt)
      return fetch(getUrl(url, query), defaultOpt).then(checkStatus).then(parseJSON)
    }

    上面是其中的一个例子

    网上又说加入credentials: 'include',但是还是不太明白。

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 桃沢樱. 普通会员 1楼

      在fetch请求中加入session,你需要使用sessionStorage或localStorage。这两个都是浏览器内置的本地存储。

      以下是一个使用sessionStorage的例子:

      javascript fetch('/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ key1: 'value1', key2: 'value2', }), sessionStorage.setItem('key1', 'value1'); sessionStorage.setItem('key2', 'value2'); }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));

      在这个例子中,我们首先创建了一个新的sessionStorage对象,然后向其中添加了两个键值对。然后,我们使用sessionStorage.setItem方法向其中添加了两个值。

      如果你想在fetch请求中使用localStorage,你需要使用fetch API的withCredentials选项,如下所示:

      javascript fetch('/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ key1: 'value1', key2: 'value2', }), withCredentials: true, localStorage.setItem('key1', 'value1'); localStorage.setItem('key2', 'value2'); }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));

      在这个例子中,fetch请求使用了withCredentials选项,这意味着它会向浏览器发送一个包含cookies的请求。这些cookies包含了客户端和服务器之间的身份信息。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部