JSONP

利用script标签

  • 只有get请求
    • 不安全
    • 有缓存
    • 数据大小有限制
  • 客户端
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script>
      $.ajax({
          url: 'http://127.0.0.1:8001/list',
          method: 'get',
          dataType: 'jsonp',
          success: res => {
              console.log(res);
          }
      });
    </script>
    
  • 后台
    let express = require('express'),
      app = express();
    app.listen(8001, _ => {
      console.log('OK!');
    });
    app.get('/list', (req, res) => {
      let {
          callback = Function.prototype
      } = req.query;
      let data = {
          code: 0,
          message: '测试数据'
      };
      res.send(`${callback}(${JSON.stringify(data)})`);
    });
    
    2、基于iframe的跨域解决方案

主域相同,子域不一样

  • window.name
  • document.domin
  • location.hash
  • post message

3、CORS跨域资源共享

客户端

import axios from 'axios';
import qs from 'qs';
axios.defaults.baseURL = "http://127.0.0.1:3000";
axios.defaults.timeout = 10000;
axios.defaults.withCredentials = true;

/*
 * 设置请求传递数据的格式(看服务器要求什么格式)
 * x-www-form-urlencoded
 */
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = data => qs.stringify(data);

/*
 * 设置请求拦截器 
 * TOKEN校验(JWT):接收服务器返回的token,存储到vuex/本地存储中,每一次向服务器发请求,我们应该把token带上
 */
axios.interceptors.request.use(config => {
    let token = localStorage.getItem('token');
    token && (config.headers.Authorization = token);
    return config;
}, error => {
    return Promise.reject(error);
});

/*
 * 响应拦截器 
 */
axios.interceptors.response.use(response => {
    return response.data;
}, error => {});

export default axios;

服务器

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "";
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Headers", "PUT,POST,GET,DELETE,OPTIONS,HEAD");
    res.header("Access-Control-Allow-Methods", "Content-Type,Content-Length,Authorization, Accept,X-Requested-With");
    req.method === 'OPTIONS' ? res.send('CURRENT SERVICES SUPPORT CROSS DOMAIN REQUESTS!') : next();
});

4、基于http proxy实现跨域请求

开发时候用proxy,部署用nginx反向代理

results matching ""

    No results matching ""