• cross-domain


     1   // GET
     2   jsonp = () => {
     3     let url = "http://xxx";
     4     fetch(url).then(function (response) {
     5       return response.json()
     6     }).then((json) => {
     7       console.log('parsed json', json);
     8       document.getElementById("demo").innerHTML = json.result[0].title;
     9     }).catch(function (ex) {
    10       console.log('parsing failed', ex)
    11     })
    12   };
    13   jsonp()
     1   // POST
     2   jsonp = () => {
     3     let postData = {
     4       account: 'xxx',
     5       password: 'xxx',
     6       name: 'xx',
     7       url_back: 'http://xxxxx'
     8     };
     9     fetch('http://xxxxx', {
    10       method: 'POST',
    11       mode: 'cors',
    12       credentials: 'include',
    13       headers: {
    14         'Content-Type': 'application/x-www-form-urlencoded'
    15       },
    16       body: JSON.stringify(postData)
    17     }).then(function (response) {
    18       console.log(response);
    19     });
    20   };
    21   jsonp()
         function postData(url, data) {
            // Default options are marked with *
            return fetch(url, {
              cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
              /**
               * omit: 默认值,忽略cookie的发送
               * same-origin: 表示cookie只能同域发送,不能跨域发送
               * include: cookie既可以同域发送,也可以跨域发送
               **/
              credentials: 'same-origin', // include, same-origin, *omit
              headers: {
                'user-agent': 'Mozilla/4.0 MDN Example',
                'content-type': 'application/json',
                'Authorization': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ3ZW5jaGVuZyIsImV4cCI6MTU3MjgyOTc1MCwiaWF0IjoxNTcyMjI0OTUwfQ.ORKZQejDq_E2KvbVF6efHrGJuhk0xRubbmSn0VH4sys-JnavGeKMEWDMKwzYvRO-L8-9SyXwbQn2MCaYZpE5jA'
              },
              method: 'GET', // *GET, POST, PUT, DELETE, etc.
              /**
               * same-origin:该模式是不允许跨域的,它需要遵守同源策略,否则浏览器会返回一个error告知不能跨域;其对应的response type为basic。
               * cors: 该模式支持跨域请求,顾名思义它是以CORS的形式跨域;当然该模式也可以同域请求不需要后端额外的CORS支持;其对应的response type为cors。
               * no-cors: 该模式用于跨域请求但是服务器不带CORS响应头,也就是服务端不支持CORS;这也是fetch的特殊跨域请求方式;其对应的response type为opaque。
               **/
              mode: 'cors', // no-cors, cors, *same-origin
              redirect: 'follow', // manual, *follow, error
              referrer: 'no-referrer', // *client, no-referrer
              // body: JSON.stringify(data), // must match 'Content-Type' header
            }).then(response => response.json()) // parses response to JSON
          }
    
          postData('http://xxx.com.cn/api/market-data-query/main/mainListMbile?pageNum=1&pageSize=15&search=', {
              answer: 42
            }).then(data => console.log(data)) // JSON from `response.json()` call
            .catch(error => console.error(error))
          let pageNum = 1
          let pageSize = 15
          let search = ''
          let url = `http://xxx.com.cn/api/market-data-query/main/mainListMbile?pageNum=${pageNum}&pageSize=${pageSize}&${search}`
    
          fetch(url, {
            method: 'GET', // or 'PUT'
            headers: new Headers({
              'Content-Type': 'application/json',
              'Authorization': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ3ZW5jaGVuZyIsImV4cCI6MTU3MjgyOTc1MCwiaWF0IjoxNTcyMjI0OTUwfQ.ORKZQejDq_E2KvbVF6efHrGJuhk0xRubbmSn0VH4sys-JnavGeKMEWDMKwzYvRO-L8-9SyXwbQn2MCaYZpE5jA'
            })
          }).then(res => res.json()).catch(error => console.error('Error:', error)).then(response => console.log('Success:', response))

    检测请求是否成功

          fetch('https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3908228140,1288170988&fm=58').then(function (response) {
            if (response.ok) {
              return response.blob()
            }
            throw new Error('Network response was not ok.')
          }).then(function (myBlob) {
            var objectURL = URL.createObjectURL(myBlob)
            document.getElementById('myImage').src = objectURL
          }).catch(function (error) {
            console.log('There has been a problem with your fetch operation: ', error.message)
          })

    axios

    main.js

    1 import axios from 'axios'
    2 
    3 Vue.prototype.$axios = axios
    4 axios.defaults.baseURL = '/api'
    5 axios.defaults.headers.post['Content-Type'] = 'application/json'

    修改config文件夹下的index.js文件,在proxyTable中加上如下代码:

    1 proxyTable: {
    2   '/api':{
    3     target: "https://c.y.qq.com/v8/fcg-bin",
    4     changeOrigin:true,
    5     pathRewrite:{
    6       '^/api':''
    7     }
    8   }
    9 },

    请求

     1   methods: {
     2     _getRecommend () {
     3       this.$axios.get('/fcg_myqq_toplist.fcg', {
     4         params: {
     5           g_tk: 5381,
     6           uin: 0,
     7           format: 'json',
     8           inCharset: 'utf-8',
     9           outCharset: 'utf-8',
    10           notice: 0,
    11           platform: 'h5',
    12           needNewCode: 1
    13         },
    14         headers: {'authorization': this.token}
    15       }).then((res) => {
    16         console.log(res.data)
    17       }).catch((err) => {
    18         console.log(err)
    19       })
    20     }
    21   },
    22   mounted () {
    23     this._getRecommend()
    24   }

    使用 http-proxy-middleware

    npm i http-server -g

    app.js

    let express = require("express");
    let proxy = require("http-proxy-middleware");
    
    let app = express();
    
    app.use("/api", proxy({ target: "https://cnodejs.org", changeOrigin: true }));
    
    app.listen(8080);

    运行

    node app.js

    浏览器访问localhost:8080/api 就会获取到 cnodejs官网的数据, 使用相对路劲的api,直接点击也会通过代理跳转拿到数据

  • 相关阅读:
    Python中常用的模块(sys模块)
    Python中常用的模块(OS模块)
    Python中常用的模块(time模块)
    Python中常用的模块(random模块)
    Python生成器详解
    Python装饰器详解
    python 两个list 求交集,并集,差集
    数据库中的视图索引
    数据库中的外键和主键理解
    mssql学习
  • 原文地址:https://www.cnblogs.com/ronle/p/10753655.html
Copyright © 2020-2023  润新知