使用nodejs koa对接口进行转发操作

nodejs yekong

最近有个项目的接口前端是没有办法直接请求的,需要后端进行处理,但是客户那边的后端不知道是什么原因一直没处理成功,今天实在是等不及了,就拦到自己这边处理了。
直接使用Nginx是不可行的,于是就想到了使用转发处理,后端请求接口,将请求到的数据返回给前端,因为我是前端所以用的是nodejs的koa插件进行操作处理的。

逻辑代码

大概的逻辑代码如下,记录一下。可能以后会再次遇到类似的情况。

const Koa = require('koa');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const fetch = require('node-fetch')
const cors = require('koa-cors')
const app = new Koa();
const token = '9d3ac0263cccb4f37d717049c1119f00'
const host = 'https://www.wanjunshijie.com'
app.use(cors())

app.use(async (ctx, next) => {
    console.log(`Process ``{ctx.request.method} ``{ctx.request.url}...`);
    await next();
});
// 充电桩充电订单 时间段、计费、能耗(默认当天所有订单)
router.get('/apiservices/charging/energy_bill', async (ctx, next) => {
    if (ctx.request.query.startTime && ctx.request.query.endTime) {
        var startTime = ctx.request.query.startTime
        var endTime = ctx.request.query.endTime
        var url = host + "/apiservices/charging/energy_bill?token=" + token + "&startTime=" + startTime + "&endTime=" + endTime
        var data = await getData(url)
        ctx.body = {
            "code": 1,
            "data": data,
            "msg": "请求成功"
        }
    } else {
        ctx.body = {
            "data": {
                "code": 0,
                "data": [],
                "msg": "请选择开始时间和结束时间"
            }
        }
    }
});
app.use(bodyParser());
// add router middleware:
app.use(router.routes());
app.listen(3400);
console.log('app started at port 3400...');

async function getData(url) {
    var response = await fetch(url, {
        "headers": {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Host": "www.wanjunshijie.com",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36",
        },
        "referrerPolicy": "strict-origin-when-cross-origin",
        "method": "GET",
        "mode": "cors"
    })
    var responseData = await response.json()
    return responseData
}


喜欢