解决跨域问题常用的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);
            }
        });

二: 跨域资源共享(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, t'

例子(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-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

三: 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 '*/*';
        } 
    }

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);
  }
});

猜你喜欢

转载自blog.csdn.net/qq_28299311/article/details/88546702