当前位置:   article > 正文

解决跨域问题常用的3种方案_解决跨域的三种方法

解决跨域的三种方法

一: ajax jsonp

缺点:

只能实现get一种请求。
后端数据必须做处理, 用方法(这里就是callback)包裹数据

例子(jquery):
 $.ajax({
            type: 'get',
            async: false,
            url: "127.0.0.1:8080",
            data:data,
            dataType: 'jsonp',//注意的地方
            jsonp: 'callback',
            jsonpCallback: 'data',
            success: function (data) {
                console.log(data)
            },
            error: function (err) {
                console.error('ajax get request fail:', err);
            }
        });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

二: 跨域资源共享(CORS)

只需在后端设置请求头:
 // 如果需要http请求中带上cookie,需要前后端都设置credentials,且后端设置指定的origin
    'Access-Control-Allow-Origin': '*'
    'Access-Control-Allow-Credentials': true
    'Access-Control-Request-Method': 'PUT,POST,GET,DELETE,OPTIONS'
    'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept, Authorization'

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
例子(nodejs):
var express = require('express');
var app = express();

//跨域配置
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

三: nginx反向代理

假设接口url为: 127.0.0.1:7001/api/test/index
访问的url为:127.0.0.1:7070

nginx配置:
  server {
        listen       7070;   #nginx监听的端口
        server_name  localhost; #nginx代理的域名
        location  /{
            index  index.html index.html;
        } 
        
        location  /api{    #只要访问带api的都会进这里
           rewrite  ^/api/(.*)$ /$1 break;         #利用正则进行匹配
           proxy_pass  http://127.0.0.1:7001/api;
           proxy_set_header authorization $http_authorization;#设置请求头
        #    proxy_set_header accept '*/*';
        } 
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
js:
$.ajax({
  type: 'get',
  async: true,
  url: "api/api/test/index",//注意这里的路径
  dataType: 'json',
  headers: {
      'Authorization':"123456",
  },
  success: function (ret) {
      console.log("成功!",ret);
  },
  error: function (err) {
      console.error('ajax get request fail:', err);
  }
});

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/865578
推荐阅读
相关标签
  

闽ICP备14008679号