Skip to content

Commit 147b647

Browse files
committed
add parameterized routing example
1 parent a412362 commit 147b647

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"scripts": {
3+
"start": "node server.js"
4+
},
5+
"dependencies": {
6+
"accepts": "1.3.3",
7+
"next": "*",
8+
"path-match": "1.2.4"
9+
}
10+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import React, { Component } from 'react'
2+
3+
export default class extends Component {
4+
static getInitialProps ({ query: { id } }) {
5+
return { id }
6+
}
7+
8+
render () {
9+
return <div>
10+
<h1>My {this.props.id} blog post</h1>
11+
<p>
12+
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
13+
tempor incididunt ut labore et dolore magna aliqua.
14+
</p>
15+
</div>
16+
}
17+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import React from 'react'
2+
import Link from 'next/link'
3+
4+
export default () => (
5+
<ul>
6+
<li><Link href='/blog?id=first' as='/blog/first'><a>My first blog post</a></Link></li>
7+
<li><Link href='/blog?id=second' as='/blog/second'><a>My second blog post</a></Link></li>
8+
<li><Link href='/blog?id=last' as='/blog/last'><a>My last blog post</a></Link></li>
9+
</ul>
10+
)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const { createServer } = require('http')
2+
const { parse } = require('url')
3+
const next = require('next')
4+
const accepts = require('accepts')
5+
const pathMatch = require('path-match')
6+
7+
const app = next({ dev: true })
8+
const handle = app.getRequestHandler()
9+
const route = pathMatch()
10+
const match = route('/blog/:id')
11+
12+
app.prepare()
13+
.then(() => {
14+
createServer((req, res) => {
15+
const accept = accepts(req)
16+
const type = accept.type(['json', 'html'])
17+
if (type === 'json') {
18+
handle(req, res)
19+
return
20+
}
21+
22+
const { pathname } = parse(req.url)
23+
const params = match(pathname)
24+
if (params === false) {
25+
handle(req, res)
26+
return
27+
}
28+
29+
app.render(req, res, '/blog', params)
30+
})
31+
.listen(3000, (err) => {
32+
if (err) throw err
33+
console.log('> Ready on http://localhost:3000')
34+
})
35+
})

0 commit comments

Comments
 (0)