Fork me on GitHub

koa学习-jsonp实现

原生koa2实现jsonp

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
const koa = require('koa');
const app = new koa();
app.use(async (ctx) => {
// 判断是否为jsonp的请求
if (ctx.method === 'GET' && ctx.url.split('?')[0] === '/getData.jsonp') {
// 获取jsonp的callback
let callbackName = ctx.query.callback || 'callback';
let returnData = {
success: true,
data: {
text: 'this is a jsonp api',
time: new Date().getTime()
}
}
// jsonp的script字符串
let jsonpStr = `;${callbackName}(${JSON.stringify(returnData)})`;
// 用text/javascript,让请求支持跨域获取
ctx.type = 'text/javascript';
// 输出jsonp字符串
ctx.body = jsonpStr
} else {
ctx.body = 'hello jsonp';
}
});
app.listen(3004, () => {
console.log('[demo] jsonp is starting at port 3004')
});

koa-jsonp中间件实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const koa = require('koa');
const jsonp = require('koa-jsonp');
const app = new koa();
app.use(jsonp());
app.use(async (ctx) => {
let returnData = {
success: true,
data: {
text: 'this is a jsonp api',
time: new Date().getTime(),
}
};
// 直接输出json
ctx.body = returnData;
});
app.listen(3004, () => {
console.log('[demo] jsonp is starting at port 3004')
});

参考文档:
koa-note
koa-jsonp

-------------本文结束感谢您的阅读,如果本文对你有帮助就记得给个star-------------
Donate comment here