implement this.fetch (#178)

This commit is contained in:
Rich Harris
2018-03-17 19:21:25 -04:00
parent cf6621b83c
commit 1e8d7d10ab
8 changed files with 116 additions and 1 deletions

View File

@@ -43,6 +43,13 @@ global.fetch = (url, opts) => {
const middlewares = [
serve('assets'),
// set test cookie
(req, res, next) => {
res.setHeader('Set-Cookie', 'test=woohoo!; Max-Age=3600');
next();
},
// emit messages so we can capture requests
(req, res, next) => {
if (!pending) return next();

View File

@@ -0,0 +1,12 @@
<h1>{{message}}</h1>
<script>
export default {
preload({ query }) {
console.log(`here ${this.fetch}`);
return this.fetch(`credentials/test.json`, {
credentials: query.creds
}).then(r => r.json());
}
};
</script>

View File

@@ -0,0 +1,28 @@
export function get(req, res) {
const cookies = req.headers.cookie
? req.headers.cookie.split(/,\s+/).reduce((cookies, cookie) => {
const [pair] = cookie.split('; ');
const [name, value] = pair.split('=');
cookies[name] = value;
return cookies;
}, {})
: {};
if (cookies.test) {
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
message: cookies.test
}));
} else {
res.writeHead(403, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
message: 'unauthorized'
}));
}
}

View File

@@ -10,6 +10,7 @@
<a href='redirect-from'>redirect</a>
<a href='blog/nope'>broken link</a>
<a href='blog/throw-an-error'>error link</a>
<a href='credentials?creds=include'>credentials</a>
<a rel=prefetch class='{{page === "blog" ? "selected" : ""}}' href='blog'>blog</a>
<div class='hydrate-test'></div>

View File

@@ -533,6 +533,32 @@ function run({ mode, basepath = '' }) {
assert.equal(title, 'Stored title');
});
});
it('sends cookies when using this.fetch with credentials: "include"', () => {
return nightmare.goto(`${base}/credentials?creds=include`)
.page.title()
.then(title => {
assert.equal(title, 'woohoo!');
});
});
it('does not send cookies when using this.fetch without credentials', () => {
return nightmare.goto(`${base}/credentials`)
.page.title()
.then(title => {
assert.equal(title, 'unauthorized');
});
});
it('delegates to fetch on the client', () => {
return nightmare.goto(base).init()
.click('[href="credentials?creds=include"]')
.wait(100)
.page.title()
.then(title => {
assert.equal(title, 'woohoo!');
});
});
});
describe('headers', () => {