-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
75 lines (65 loc) · 2.3 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const apiPaths = {
'/api': {
target: 'https://api.clip-viewer-lite.com',
pathRewrite: {
'^/api': '/'
},
changeOrigin: true,
logLevel: 'debug',
onProxyReq: (proxyReq, req, res) => {
//console.log('Proxying request:', req.method, req.url);
//console.log('Original headers:', req.headers);
// APIキーをヘッダーに追加
if (!proxyReq.getHeader('X-API-Key')) {
const apiKey = process.env.NEXT_PUBLIC_CLIP_VIEWER_LITE_API_KEY;
proxyReq.setHeader('X-API-Key', apiKey);
//console.log('API Key added:', apiKey);
}
//console.log('Proxy headers before modification:', proxyReq.getHeaders());
// POSTリクエストの場合、ボディを転送
if (req.method === 'POST' && req.body) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
//console.log('Proxy headers after modification:', proxyReq.getHeaders());
},
onProxyRes: (proxyRes, req, res) => {
//console.log('Proxy response status:', proxyRes.statusCode);
//console.log('Proxy response headers:', proxyRes.headers);
let body = '';
proxyRes.on('data', function (chunk) {
body += chunk;
});
proxyRes.on('end', function () {
//console.log('Proxy response body:', body);
});
},
onError: (err, req, res) => {
console.error('Proxy error:', err);
}
}
}
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
const { pathname } = parsedUrl
if (pathname.startsWith('/api')) {
//console.log('Handling API request:', pathname);
const proxy = createProxyMiddleware(apiPaths['/api']);
return proxy(req, res);
}
handle(req, res, parsedUrl)
}).listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})