-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
37 lines (34 loc) · 1.18 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const { parse } = require('url');
const next = require('next');
const { createServer } = require('http');
const app = next({ dev: true });
const port = 3000;
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
// Enable CORS in development
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const { pathname, query } = parse(req.url, true);
if (pathname === '/' || pathname.startsWith('/static') || pathname.startsWith('/_next')) {
handle(req, res);
} else if (pathname.endsWith('/')) {
// Respond to `foo/`, matching production behavior
// (If next could be configured to do this we could delete this entire file)
app.render(req, res, pathname.slice(0, -1), query);
} else {
// 404 for page `foo` even if `foo/` exists to notice link mistakes more easily in dev
app.render404(req, res);
}
}).listen(port, err => {
if (err) {
throw err;
}
console.log(`Next.js server started at http://localhost:${port}`);
});
});