当前位置:网站首页>CROS和JSONP配置
CROS和JSONP配置
2022-08-05 08:06:00 【cjx177187】
跨域
1.egg-cors框架提供了 egg-cors 插件来实现cors跨域请求。
//1.下载
cnpm i --save egg-cors
//2.开启插件
// config/plugin.js文件
cors:{
enable: true,
package: 'egg-cors',
}
//3.配置插件
// config/config.default.js文件
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
}
//默认origin只支持一个域名或者*表示全部,如果想支持具体的多个指定域名可以如下设置:
config.cors = {
// origin: ['http://localhost'],
origin:function(ctx) { //设置允许来自指定域名请求
console.log(ctx);
const whiteList = ['http://www.baidu.com','http://www.hqyj.com'];
let url = ctx.request.header.origin;
if(whiteList.includes(url)){
return url;
}
return 'http://localhost' //默认允许本地请求可跨域
},
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};
//4.使用:
//router.js文件
router.get('/cors',controller.home.cors)
//home.js文件
async cors(){
this.ctx.body={ info:"这个接口可以通过跨域访问"}
}
5. 注意:跨域前端请求时需要携带跨域凭证,不然缓存会失效
前端网络请求时配置:
原生ajax:
xhr.withCredentials = true;
axios:
axios.post(url,{},{ withCredentials:true}).then((res)=>{})
后端配置:
config.cors = {
origin: '具体的ip和端口 不能写* ',
credentials:true
}
2.实现jsonp接口
//如果前端的参数中有cb=fn参数(jsonp接口参数),将会返回JSONP格式的数据,否则返回JSON格式的数据。
//1.配置:
// config/config.default.js文件
config.jsonp = {
callback: 'cb', // 识别 query 中的 `cb` 参数
limit: 100, // 函数名最长为 100 个字符
};
//2.写接口
// app/router.js
module.exports = app => {
const jsonp = app.jsonp();
app.router.get('/api/posts', jsonp, app.controller.posts.list);
};
也可以直接在jsonp方法中直接配置,功能一样:
//如果前端的参数中有cb=fn参数(jsonp接口参数),将会返回JSONP格式的数据,否则返回JSON格式的数据。
// app/router.js文件
module.exports = app => {
const jsonp = app.jsonp({
callback: 'cb',
limit: 100,
});
app.router.get('/api/posts', jsonp, app.controller.posts.list);
};
边栏推荐
- Use of thread pool (combined with Future/Callable)
- TRACE32——通用寄存器查看与修改
- Fiddler tool explanation
- MySQL 数据库 报错 The server quit without updating PID file (/var/lib/mysql/localhost.localdomain.pid)
- MobileNetV2架构解析
- Redis implements distributed lock-principle-detailed explanation of the problem
- Version number naming convention
- SQL SERVER关于主从表触发器设计
- Codeforce 8.1-8.7做题记录
- 奇怪的Access错误
猜你喜欢
随机推荐
Chapter 12 贝叶斯网络
TRACE32——加载符号表信息用于调试
[转帖]嫁人一定要嫁工资至少比你高3571.4元的男士
高效使用数码相机的诀窍
软件系统测试和验收测试有什么联系与区别?专业软件测试方案推荐
TRACE32——Break
[Structure internal power practice] Structure memory alignment (1)
php向mysql写入数据失败
监听浏览器刷新操作
TRACE32——C源码关联1
作为一个男人必须明白的22个道理
字符串提取 中文、英文、数字
Stored procedure writing experience and optimization measures
【结构体内功修炼】枚举和联合的奥秘(三)
Mysql 死锁和死锁的解决方案
双向循环带头链表
请问my sql如何把两个表的内容集合在一起啊?
SVG Star Wars Style Toggle Toggle Button
JVM运行流程,运行时数据区,类加载,垃圾回收,JMM解析
关于MP3文件中找不到TAG标签的问题









![[Structural Internal Power Cultivation] The Mystery of Enumeration and Union (3)](/img/39/d20f45ccc86ebc4e5aebc8e4d0115f.png)