KOA-router封装第三方API解决跨域问题

利用koa简单封装,既可以轻松解决利用第三方接口请求引起的跨域问题,真是简单轻松。

app.js文件节选是这样的:

const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const feedback = require('./api').feed_back;
const app = new Koa()
const router = new Router()
const port = 90
router.use(bodyParser())
router.post('/api/feedback', async (ctx) => {
const r = await feedback(ctx.request.body);
ctx.type = 'text/json';
ctx.body = r;
})
app.use(router.routes()).use(router.allowedMethods())
const host = `http://localhost:${ port }`
app.listen(port, () => console.log(`server is running on ${ host }`))

api.js文件长这样:

const http = require('http')
const qs = require('querystring')
exports.feed_back = (args,done) => {
return new Promise( (resolve,reject) => {
let ctx = qs.stringify(args)
let options = {
hostname: 'xxx.com',
path: '/a/api/b',
port: '80',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const req = http.request(options,(res) => {
let resData = '';
res.setEncoding('utf8');
res.on('data', chunk => {
resData += chunk;
})
res.on('end', () => {
resolve(resData)
})
})
req.on('error', e => {
console.log('error:',e.message)
reject(e.message)
})
req.write(ctx)
req.end();
} )
}

然后,用postman请求以下,哇!妥妥的返回了数据!

NOOLDEY

本文作者:NOOLDEY

做一个诗情画意的码农,皮皮猪,我们走!

原文链接: http://zhuweisheng.com.cn/framework/koa-router-api/

本站文章如无特殊声明均为原创,创作不易,转载请注明来源,谢谢!