前端跨域

1.jsonp实现跨域

 

 1 <script>
 2 var script = document.createElement('script');
 3 script.type = 'text/javascript';
 4 
 5 // 传参并指定回调执行函数为(&callback=onBack)
 6 script.src = 'http://www.....:8080/login?user=admin&callback=onBack';
 7 document.head.appendChild(script);
 8 
 9 // 回调执行函数
10 function onBack(res) {
11     alert(JSON.stringify(res));
12 }
13 </script>

 

2.设置代理

  [vue]配置跨域|vue.config.js

 

 1 module.exports = {
 2     devServer: {
 3         open: true,
 4         host: 'localhost',
 5         port: 8000,
 6         https: false,
 7         //以上的ip和端口是我们本机的;下面为需要跨域的
 8         proxy: { //配置跨域
 9             '/api': {
10                 target: 'http://127.0.0.1:8000/api/', //这里后台的地址模拟的;应该填写你们真实的后台接口
11                 ws: true,
12                 changOrigin: true, //允许跨域
13                 pathRewrite: {
14                     '^/api': '' //请求的时候使用这个api就可以
15                 }
16             }
17         }
18     }
19 }

 

3.后端设置跨域(node)

  1.允许所有域名

 

 1 app.all("*", function(req, res, next) {
 2     //设置允许跨域的域名,*代表允许任意域名跨域
 3     res.header("Access-Control-Allow-Origin", "*");
 4     //允许的header类型
 5     res.header("Access-Control-Allow-Headers", "content-type");
 6     //跨域允许的请求方式 
 7     res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
 8     if (req.method.toLowerCase() == 'options')
 9         res.send(200); //让options尝试请求快速结束
10     else
11         next();
12 })

 

  2.指定域名 http://www.xxxxxxx.com

 

 1 app.all("*",function(req,res,next){
 2     //设置允许跨域的域名,*代表允许任意域名跨域
 3     res.header("Access-Control-Allow-Origin","http://www.zhangpeiyue.com");
 4     //允许的header类型
 5     res.header("Access-Control-Allow-Headers","content-type");
 6     //跨域允许的请求方式 
 7     res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
 8     if (req.method.toLowerCase() == 'options')
 9         res.send(200);  //让options尝试请求快速结束
10     else
11         next();
12 }

 

posted @ 2022-12-14 10:35  TM_cc  阅读(40)  评论(0)    收藏  举报