模擬 Cookie 回應
雖然 Mirage 允許在回應中設定標頭,但 XMLHttpRequest 規範明確禁止存取 Set-Cookie
和 Set-Cookie2
標頭。因此,Mirage 回應無法透過標頭設定 Cookie。
不過,您可以在路由函式處理器中設定 Cookie,以模擬在瀏覽器層級接收來自 Ajax 呼叫的 Cookie
this.post("/users/login", (schema) => {
// log in for 24 hours
let now = new Date()
let cookieExpiration = new Date(now.getTime() + 24 * 3600 * 1000)
document.cookie = `remember_me=cookie-content-here; domain=.dev-domain; path=/; expires=${cookieExpiration.toUTCString()};`
return schema.users.find(1)
})
現在,您的 JavaScript 用戶端程式碼將可以存取使用 document.cookie
設定的任何 Cookie。