zoukankan      html  css  js  c++  java
  • vue+vue-resource设置请求头(带上token)

    前言

      有这样的一个需求,后台服务器要求把token放在请求头里面

      嗯一般是通过data里面通过参数带过去的

    第一种方法

      全局改变:

      Vue.http.headers.common['token'] = store.state.token;
      之前是吧token刚在data里面的
      是我封装的一个get 请求,亲测有用。现在我们项目就是用的这一种

          

      然后放一个请求成功的实例

      首先会先发一个 OPTIONS 预请求

      

      然后发出正式请求

      

    第二种方法:

      不能局限于一种方法嘛!

      第二种方法是:在Vue实例中设置

    var vm = new Vue({
      el:'#app',
      data:{
       showList: true,
       title: null
      },
      http: {
        root: '/',
        headers: {
          token: token
        }
      }
    })

    第三种方法:在拦截器中设置  vue interceptors 设置请求头

    Vue.http.interceptors.push((request, next) => {
        request.headers.set('token', token); //setting request.headers
        next((response) => {
          return response
       })
    })

    还可以这样

      在在main.js添加过滤器

    Vue.http.interceptors.push((request,next)=>{
     //request.credentials = true; // 接口每次请求会跨域携带cookie
     //request.method= 'POST'; // 请求方式(get,post)
     //request.headers.set('token','111') // 请求headers携带参数
     
     next(function(response){
      return response;
     
     });
    })

    Fannie总结

      后面的方法要自己去实践哦,我用的是第一种。

      然后再次提醒一下,你们自家的服务器要支持这样传token哦~

      不然会报个错的,像下面这样

    Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

       拜拜了。

  • 相关阅读:
    针对Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1的解决方案
    MAC配置C++运行环境
    Keras 模型相关操作
    微信小程序 WXS
    vue 长列表优化
    webpack4 SplitChunks插件 代码拆分
    node path api
    mysql的模型依赖说明
    MySQL和MyCat replace
    SQL Server中WITH(NOLOCK)提示用在视图上会怎样(转载)
  • 原文地址:https://www.cnblogs.com/ifannie/p/11046835.html
Copyright © 2011-2022 走看看