We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在项目复杂的业务场景,有时候需要在前端跨域获取数据,这时候提供数据的服务就需要提供跨域请求的接口,通常是使用JSONP的方式提供跨域接口。
var koa = require('koa') var app = new koa() app.use(async (ctx) => { if (ctx.method === 'GET' && ctx.url.split('?')[0] === '/getData.jsonp') { // 获取jsonp的callback参数 let callbackName = ctx.query.callback || 'callback' console.log(callbackName) 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' ctx.body = jsonpStr } else { ctx.body = 'hello jsonp' } }) app.listen(3000, ()=>{ console.log('run on 3000 port') })
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(3000, () => { console.log('[demo] jsonp is starting at port 3000') })
现在用到中间件有:
现在掌握了的API有:
现在掌握了的Node原生API有:
ctx.cookies.set('name', 'ljm', { domain: 'localhost', // 写cookie所在的域名 path: '/index', // 写cookie所在的路径 maxAge: 10 * 60 * 1000, // cookie有效时长 expires: new Date('2017-02-15'), // cookie失效时间 httpOnly: false, // 是否只用于http请求中获取 overwrite: false // 是否允许重写 } )
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原生Koa实现JSONP
中间件实现JSONP
总结
现在用到中间件有:
现在掌握了的API有:
现在掌握了的Node原生API有:
// koa的ctx自带读取 和 写入 cookie的方法
// 遗憾的是跟post请求一样,koa并没有提供读取 和 写入session 的方法。只能通过自己实现或者通过第三方中间件实现:
The text was updated successfully, but these errors were encountered: