Vue 携带 token,浏览器报错

浏览器提示如下:
已拦截跨源请求:同源策略禁止读取位于 http://127.0.0.1:8000/project_list 的远程资源。(原因:CORS 预检响应的 'Access-Control-Allow-Headers',不允许使用头 'token')。

django 后端不验证用户时,即不需要用token时, 就不会报这错误,
不验证用户,可以正常得到 后端数据

login.vue 交互代码, 可以正常登录. 但登录后,打开其它vue页面 从后端获取数据时, 就报上面的错误

  methods: {
    async onSubmit () {
      const { data: res } = await this.$http.post('login/', { username: this.username, password: this.password }) //, { emulateJSON: true }
      window.sessionStorage.setItem('token', res.token)  #  存token 
    }
  }

vue main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

const app = createApp(App)
app.config.globalProperties.$http = axios
axios.defaults.baseURL = 'http://127.0.0.1:8000/'
axios.defaults.withCredentials = false  # 这个改成True 登录会失败, 不要这行代码,也报上面的错,
axios.interceptors.request.use(config => { // 拦截器,请求头统一加 token
  if (sessionStorage.getItem('token')) {
  // 在请求头加入token
    config.headers.token = sessionStorage.getItem('token')  
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

app.use(router).mount('#app')

下面是这个后端 django auth api , 控制台 打印 token 返回None,相当后端没获取到token ,或者获取的方法不对

class Authenticate(BaseAuthentication):
    def authenticate(self, request):
        token=request.GET.get('token')
        print('@@@',token)        # 控制台输出 None
        token_obj=UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed
        return (token_obj.user,token_obj)
    def authenticate_header(self, request):
        pass


token请求头不是浏览器默认有的(如Accept-Language,Referer,User-Agent等),发送自定义的请求头,在跨域请求时,服务器端需要使用Access-Control-Allow-Headers响应头设置允许哪些自定义的请求头

django 如何添加自定义响应头参考这篇文章


有帮助麻烦点个采纳【本回答右上角】,谢谢~~

img

哈喽,token试试这样设置

config.headers.common.Authorization = 'Bearer ' + sessionStorage.getItem('token') 

问题找到了,上面在后端获取表头的方法错了,

class Authenticate(BaseAuthentication):
    def authenticate(self, request):
       # token=request.GET.get('token')  这个是错的
        token = request.META.get('HTTP_TOKEN')  # 要这样后端才能获取表头的token ,而且要加HTTP_   全部要大写,真坑
        print('@@@',token)       
        token_obj=UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed
        return (token_obj.user,token_obj)
    def authenticate_header(self, request):
        pass


让你们后端或者运维在跨域代理配置中增加请求头参数 【token】
Access-Control-Allow-Headers: "token"

有用望采纳