Vue 0 basic learning route (15)-Graphical in-depth detailed description of Vue asynchronous requests and cross-domain, forward proxy local development and detailed cases (with detailed case code analysis process and version iteration process)

1. Key Refinement

  • Asynchronous request
    • axios
  • Cross-domain

2. Koa builds backend service

Make a local backend:

yarn init

yarn add koa koa-router

Xiaodi won’t go into details here. If you have any questions node, blogplease see Xiaodi about it. I will copy the previous code directly and execute the yarninstallation dependency.

Insert picture description here

\server01\app.js

const Koa = require('koa');
const KoaRouter = require('koa-router');
const KoaBodyParser = require('koa-bodyparser')

let datas = {
    
    
    items: require('./data/items.json'),
    users: require('./data/users.json')
}

const app = new Koa();

let currentId = 20;

app.use( async (ctx, next) => {
    
    
    await next();
} );

app.use(KoaBodyParser());

const router = new KoaRouter();

router.get('/', async ctx => {
    
    
    ctx.body = 'api';
});

router.get('/items', async ctx => {
    
    
    let sort = ctx.request.query.sort || 'desc';
    let items = datas.items.sort((a, b) => sort === 'asc'  ? a.price - b.price : b.price - a.price);

    ctx.body = items;
});

router.get('/item/:id', async ctx => {
    
    
    let id = Number(ctx.params.id);
    let item = datas.items.find(item => item.id === id);

    await new Promise(resolve => {
    
    
        setTimeout(_=>resolve(), 2000);
    });

    if (!item) {
    
    
        ctx.throw(404, '没有该商品信息');
        return;
    }

    ctx.body = item;
    
});

router.post('/add', async ctx => {
    
    
    let {
    
    name} = ctx.request.body;

    if (name === '') {
    
    
        ctx.body = {
    
    
            code: 1,
            message: '商品名称不能为空'
        }
        return;
    }

    let newData = {
    
    
        id: currentId++,
        name
    };

    datas.items.unshift(newData);

    ctx.body = {
    
    
        code: 0,
        message: '提交成功',
        data: newData
    }
})

app.use( router.routes() );

app.listen(7777);

Insert picture description here

3. Asynchronous request

In actual application development, it is a very common requirement to interact with the backend and make asynchronous requests

3.1 axios

npm i axios
yarn add axios

Insert picture description here

3.2 Request

// home.vue
<template>
  <div class="home">
    Home
  </div>
</template>

<script>
import axios from 'axios';
export default {
     
     
  name: 'home',
  data() {
     
     
    return {
     
     
      items: []
    }
  },
  created() {
     
     
    axios({
     
     
      url: 'http://localhost:7777/items'
    }).then(res => {
     
     
      this.items = res.data;
    });
  }
}
</script>

3.3 example01

\app\src\views\Home.vue

<template>
    <div>
        Home
    </div>
</template>

<script>
    import axios from 'axios'

    export default {
     
     
        name: "Home",

        data() {
     
     
            return {
     
     
                items: []
            }
        },

        async created() {
     
     
            let rs= await axios({
     
     
                url:'http://localhost:7777/items'
            });

            this.items = rs.data;

            console.log(this.items);
        }
    }
</script>

Because of the cross-domain error! The general online solution is configuration 代理服务器, or to corsdeal with cross-domain issues.

For cross-domain local development, let's set up the local vueconfiguration. (In the previous article, I talked about vue配置how to configure files)

Insert picture description here

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a1.73
Branch: branch05

commit description: a1.73 (example01-cross-domain problem with axios receiving data)

day : a1.73

4. Cross-domain

vue-cli provides a built-based node of the webserver , we can use it to provide a proxy service to proxy cross-domain requests

4.1 vue.config.js

Create one in the root directory of the project vue.config.js documents, by npm run servethe time the service starts, it will read the file

4.2 Cross-domain request proxy configuration

// vue.config.js
module.exports = {
    
    
  devServer: {
    
    
    proxy: {
    
    
      '/api': {
    
    
        target: 'http://localhost:7777',
        pathRewrite: {
    
    
          '^/api': ''
        }
      }
    }
  }
}

To modify the configuration file, you need to restart the service:npm run serve

// home.vue
<script>
...
created() {
     
     
  axios({
     
     
  	url: '/api/items'
  }).then(res => {
     
     
  	this.items = res.data;
	});
}
...
</script>

4.3 example02

4.3.1 example02-1

\app\src\views\Home.vue

        async created() {
    
    
            let rs= await axios({
    
    
                url:'/items'
            });
 
            this.items = rs.data;
 
            console.log(this.items);
        }

url:'/items'The request will be devServerintercepted and proxyforwarded tohttp://localhost:7777

\ app \ vue.config.js

 
module.exports = {
    
    
 
    devServer: {
    
    
        proxy: {
    
    
            '/items': {
    
    
                target: 'http://localhost:7777'
            }
        }
    }
 
};

Insert picture description here

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a1.74
Branch: branch05

commit description: a1.74 (example02-1-to solve the cross-domain problem of axios receiving data)

day : a1.74

4.3.2 example02-2

This configuration is also not very good, because you will need to configure for each request, we can add a prefix to it, request an address and then forward.

url:'/api/items' => Add a special prefix to prevent conflicts during routing.

\app\src\views\Home.vue

        async created() {
    
    
            let rs= await axios({
    
    
                url:'/api/items'
            });
 
            this.items = rs.data;
 
            console.log(this.items);
        }

\ app \ vue.config.js

 
module.exports = {
    
    
 
    devServer: {
    
    
        proxy: {
    
    
            '/api': {
    
    
                target: 'http://localhost:7777',
                pathRewrite: {
    
    
                    '^/api': ''
                }
            }
        }
    }
 
};

Insert picture description here

The advantage there is, if there are multiple server, then the server in multiple multiple interfaces at the same time, can be carried out /api1/xx, /api2/xxand so forward multiple.

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a1.75
Branch: branch05

commit description: a1.75 (example02-2-to solve the cross-domain problem of axios receiving data 2)

day : a1.75



(To be added later)

Guess you like

Origin blog.csdn.net/u013946061/article/details/107743060