问题描述
今天遇到一个问题,是需要在请求头上加上User-Id的参数来传登陆用户的信息,然后在axios进行设置:
一、复杂方式
由于axios默认是不让ajax请求头部携带cookie,所以需要将withCredentials设置为true。   到这里之后,请求后台还是会报错的  报错提示大致内容为受到CORS策略的阻止:当请求的凭据模式为“包括”时,响应中“ Access-Control-Allow-Origin”标头的值不得为通配符“ ”。 XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。 这次解决跨域的后台需要设置Access-Control-Allow-Origin的值,不能再为‘’。 (当时我还不明白这个携带cookie的意思,这里应该是使用这个站点的cookie,有一种场景经常使用到,就是将token放在cookie中。所以需要这个站点的cookie,这样的话,后台跨域的时候只能只有一个源了,后台Access-Control-Allow-Origin不能为,所以但是我们只是在请求头设置参数user-id,可以不用将withCredentials打开的,这个也是用了第二个方式之后理解的) 前端设置withCredentials的情况下,需要设置后台两个地方,后端要设置Access-Control-Allow-Origin为你的源地址,例如http://localhost:8080,而且还要设置header(‘Access-Control-Allow-Credentials: true’);
设置请求头 Axios.defaults.headers.common[“User-Id”] = store.state.user.id;  然后发起对后台的请求,又报错   报错提示User-Id不被允许。 需要在后台设置Access-Control-Allow-Headers

二、简单方式
前端只需要设置请求头 Axios.defaults.headers.common[“User-Id”] = store.state.user.id;  然后后端解决跨域时,设置允许User-Id  此时再发起请求是成功的,但是需要前端需要请求两次  一次为请求方式为OPTIONS,目的为对请求头进行验证。此时请求头是没有user-id的;第二次请求是真正的请求,此时请求中已经带上user-id的信息 
|