鍍金池/ 問答/HTML/ axios的withCredentials問題

axios的withCredentials問題

問題描述

我想要跨域帶上cookies,為什么withCredentials: true不起作用?

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

我嘗試過axios.defaults.withCredentials = true可以起作用。
但是為什么單獨(dú)配置,沒有作用?

相關(guān)代碼

axios.post('http://101.132.138.141:8888/service/pageUsers', objectToForm({
        'currentPage': '1',
        'pageSize': '10',
        'token': '7e987daa-6c84-46d2-be26-f345dfaed8a7',
    }), {
        // 單獨(dú)配置
        withCredentials: true
    })
    .then(function(res) {
        console.log(res.data);
    })
    .catch(function(err) {
        console.error(err);
    });

實(shí)際看到的錯(cuò)誤信息又是什么?

已攔截跨源請(qǐng)求:同源策略禁止讀取位于 http://101.132.138.141:8888/service/pageUsers 的遠(yuǎn)程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。

后端已經(jīng)設(shè)置了CORS頭,但是因?yàn)闆]有附帶上cookies,所以被攔截器攔截了。

回答
編輯回答
陌南塵

withCredentials的情況下,后端要設(shè)置Access-Control-Allow-Origin為你的源地址,例如http://localhost:8080,不能是*,而且還要設(shè)置header('Access-Control-Allow-Credentials: true');

2018年9月7日 14:34