ajax 請求攜帶cookie 瀏覽器報錯

weixin_33866037發表於2018-09-17

9276502-589a2b34f6d83cda.png
image.png

翻譯一下他的意思就是說攜帶cookie的時候後臺不能設定為 *

直接上程式碼

 const Koa = require('koa');
 const route = require('koa-route');
 const cors = require('koa-cors');
const app = new Koa();

// app.use(cors());
app.use(cors({
    origin: function (ctx) {
        console.log(ctx);
        if (ctx.url == '/data') { // 攜帶cookie
            return ctx.header.origin;
        } else {
            return '*';
        }
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
app.use(route.get('/data', (ctx) => {
    console.log(ctx);
    ctx.set
    ctx.body = { data: [1, 2, 3, 4, 45, 5] };
    // return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //         resolve(ctx.body = { data: [1, 2, 3, 4, 45, 5] })
    //     }, 1000 * 60 * 2.2);
    // })
}));


app.listen(3000, () => {
    console.log('啟動成功');
});
  document.cookie = "userId=828";
document.cookie = "userName=zhangsan";
console.log(document.cookie);

const URL = 'http://127.0.0.1:3000';
// axios
axios.defaults.withCredentials = true; // 攜帶cookie
axios(URL + '/data').then((res) => {
    console.log(res.data);
});
// fetch
fetch(URL + '/data', {
    method: 'GET',
    credentials: 'include' // 允許攜帶cookie
}).then((res) => {
    console.log(res.data);
});

相關文章