解決跨域問題經常使用的3種方案

一: ajax jsonp

缺點:

只能實現get一種請求。
後端數據必須作處理, 用方法(這裏就是callback)包裹數據html

例子(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:7070node

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);
  }
});
相關文章
相關標籤/搜索