Last active
May 22, 2020 01:24
-
-
Save syuji-higa/2a06ff350281f70a9d664599771b7087 to your computer and use it in GitHub Desktop.
Node.js - API proxy server routing
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 strict' | |
const Koa = require('koa') | |
const cors = require('@koa/cors') | |
const Router = require('koa-router') | |
const axiosBase = require('axios') | |
require('colors') | |
const axios = axiosBase.create({ | |
baseURL: 'https://xxxxx.xxx/api/v1/', | |
headers: {}, | |
responseType: 'json' | |
}) | |
const app = new Koa() | |
const router = new Router() | |
const routeFunc = async (ctx, next) => { | |
let isAccess = true | |
const { method, url, body } = ctx.request | |
console.log(`[${method}: ${url}]`.yellow) | |
const _options = { method, url } | |
if (body) { | |
console.log('[REQ]'.yellow) | |
console.log(body) | |
_options.data = body | |
} | |
const res = await axios(_options).catch((err) => { | |
if (err.response) { | |
const { status, data } = err.response | |
console.log('[ERR]'.yellow) | |
// API error | |
if (typeof data === 'object') { | |
ctx.status = status | |
ctx.body = data | |
console.log(data) | |
} | |
// Server error | |
else { | |
isAccess = false | |
console.log(err.message) | |
} | |
} | |
}) | |
// Success | |
if (res) { | |
const { status, data } = res | |
ctx.status = status | |
ctx.body = data | |
console.log('[RES]'.yellow) | |
console.log(data) | |
} | |
if (isAccess) { | |
await next() | |
} | |
} | |
router | |
.get('/sample', routeFunc) | |
.post('/sample', routeFunc) | |
app | |
.use(cors()) | |
.use(router.routes()) | |
.use(router.allowedMethods()) | |
const server = app.listen('8080', 'localhost', () => { | |
const host = server.address().address | |
const port = server.address().port | |
console.log('listening at http://%s:%s', host, port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment