vue.js 跨域,教你访问一个api

什么是跨域?

一句话:你可以理解成,别人为了防止你直接访问api,攻击他们的服务器做的保护伞。

那么我们怎么解决访问题,去访问别人的数据呢?

使用《vue-反向代理》

1.下载axios安装https://github.com/axios/axios,我这里用的yarn,yarn真的超级好用

$ yarn add axios

npm 的用户可以用如下

$ npm install axios

不同的终端不同的代码大家可以直接在github中搜索axios查看安装代码


我们使用下面的代码直接复制到vscode编译器中

get

axios.get(‘你的API去掉com之前的内容').then(function(response)

{// handle successconsole.log(response);})//打印返回结果

.catch(function(error){

// handle errorconsole.log(error);}) //捕获异常

.then(function(){

// always executed}); //接下来执行

举个例子:axios。你的完整网站是:http://m.xxxxxxxxxxxxxxxxxxxxx.com/ /ajax/movieOnInfoList?token=

get里面放入:/ajax/movieOnInfoList?token=



post

axios.post('你的API去掉com之前的内容',{firstName:'Fred',lastName:'Flintstone'})

.then(function(response){console.log(response);})

.catch(function(error){console.log(error);});


vue中请求

// vue中导入import

<script>

import axios from 'axios'

export default {

  mounted() {

   axios.get("/ajax/movieOnInfoList?token=")

  .then(function (response) {

    // handle success

    console.log(response);

  })

</script>


最后创建一个vue.config文件,位置要与package。json平级,我们在vuecli的官方文档中就可以查看到相关的说明,我们直接把代码复制过来


module.exports = {

  devServer: {

    proxy: {

      '/ajax': { //这里你要设置在什么字符串中拦截代理,白话文网站最好设置com结尾后面的字符串

        target: 'http://m.xxxxxxxxxxxxxxxxxxxxx.com', //里面设置为网站地址

        // ws: true,

        changeOrigin: true

      },

      // '^/foo': {

      //   target: '<other_url>'

      // }

    }

  }

}


最后我们重启一下服务器就可以查看到结果

你可以使用

npm run serve 

或者用

yarn serve

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容