Article Directory
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
, blog
please see Xiaodi about it. I will copy the previous code directly and execute the yarn
installation dependency.
\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);
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
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 cors
deal with cross-domain issues.
For cross-domain local development, let's set up the local vue
configuration. (In the previous article, I talked about vue配置
how to configure files)
参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a1.73
Branch: branch05commit 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 serve
the 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 devServer
intercepted and proxy
forwarded tohttp://localhost:7777
\ app \ vue.config.js
module.exports = {
devServer: {
proxy: {
'/items': {
target: 'http://localhost:7777'
}
}
}
};
参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a1.74
Branch: branch05commit 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': ''
}
}
}
}
};
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/xx
and so forward multiple.
参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a1.75
Branch: branch05commit description: a1.75 (example02-2-to solve the cross-domain problem of axios receiving data 2)
day : a1.75
(To be added later)