Last active
August 26, 2019 06:05
-
-
Save d1y/9b8eddeabd3d92a4f4ff4e6472e809a6 to your computer and use it in GitHub Desktop.
[Nextjs] A nextjs middle proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| ** the nextjs link example | |
| ** currentpath: /pages/link.js | |
| */ | |
| import Link from 'next/link' | |
| import React from 'react' | |
| export default class extends React.Component { | |
| render() { | |
| return ( | |
| <> | |
| <Link href="/post" as="/post/2"> | |
| <a>link to 2</a> | |
| </Link> | |
| <> | |
| ) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| ** currentpath: /pages/path.js | |
| */ | |
| import { withRouter } from 'next/router' | |
| export default withRouter((router)=> ( | |
| <> | |
| <p>the id is { router.query.id }</p> | |
| </> | |
| )) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| ** use `koa` and `koa-router` | |
| ** https://github.com/zeit/next.js#custom-server-and-routing | |
| */ | |
| const koa = require('koa') | |
| const Router = require('koa-router') | |
| const next = require('next') | |
| // check the env is dev | |
| const dev = process.env.NODE_ENV == 'production' | |
| const app = next({ dev }) | |
| const handle = app.getRequestHandler() | |
| app.prepare() | |
| .then(()=> { | |
| const server = new Koa() | |
| const router = new Router() | |
| router.get('/path/:id', async ctx => { | |
| const id = ctx.params.id | |
| await handle( ctx.req, ctx.res, { | |
| pathname: '/path', | |
| query: { id } | |
| } | |
| ctx.respond = false | |
| }) | |
| server.use(router.routes()) | |
| server.use(async (ctx, next) => { | |
| await handle(ctx.req, ctx.res) | |
| ctx.respond = false | |
| }) | |
| server.listen(3000, () => { | |
| console.log('koa-server run in :3000') | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment