1、http协议:前端(浏览器)发送请求,服务器给予相应。
2、请求方法:get(查询)、post(添加)、put(修改)、delete(删除)
3、ajax:不刷新页面与后台交互数据
4、axios:封装好的ajax模块
5、koa:基于node的web框架
App.vue:
- <template>
- <div id="app">
- <form action="">
- <input type="text" v-model="fruit">
- <button>添加button>
- form>
-
- <ul>
- <li>香蕉
- <button>删除button>
- li>
-
- ul>
- div>
- template>
-
- <script>
- import axios from "axios";
- export default {
- data() {
- return {
- fruit: "",
- fruitList: [],
- };
- },
- methods: {
- getFruitList() {
- axios.get("http://127.0.0.1:3000/fruits").then((res) => {
- console.log(res.data);
- });
- },
- },
- created() {
- this.getFruitList();
- },
- };
- script>
因为是两个服务器,所以涉及到跨域问题。
需要提前下载好模块:
- cnpm install --save koa
- cnpm install --save koa-parser
- cnpm install --save koa-router
- cnpm install --save koa2-cors
serve.js:
- const Koa = require("koa");
- //post请求模块
- const parser = require("koa-parser");
- //设置路由
- const router = require("koa-router")();
- ///允许跨域
- const cors = require('koa2-cors');
- const app = new Koa();
-
- app.use(cors());
- app.use(parser());
- app.use(router.routes());
-
- //模拟数据库
- const fruitList = ["香蕉", "苹果", "鸭梨"];
-
- //get方法:获取水果列表
- router.get("/fruits", async ctx => {
- ctx.body = fruitList;
- })
-
- //post方法:添加水果
- router.post("/fruits", async ctx => {
- let fruit = ctx.request.body.fruit;
- fruitList.push(fruit);
- ctx.body = true;
- })
-
- //delete方法:删除水果列表
- router.delete("/fruits/:index", async ctx => {
- let index = ctx.params.index;
- fruitList.splice(index, 1);
- ctx.body = true;
- })
-
- app.listen(3000, () => {
- console.log("server is running")
- })
使用【nodemon serve.js】运行后台的js文件。
3、查看效果
修改App.vue:
- <template>
- <div id="app">
- <form @submit.prevent="postData">
- <input type="text" v-model="fruit">
- <button>添加button>
- form>
-
- <ul>
- <li v-for="item,index of fruitList" :key="index">
- {{item}}
- <button @click="del(index)">删除button>
- li>
-
- ul>
- div>
- template>
-
- <script>
- import axios from "axios";
- export default {
- data() {
- return {
- fruit: "",
- fruitList: [],
- };
- },
- methods: {
- //获取数据
- getFruitList() {
- axios.get("http://127.0.0.1:3000/fruits").then((res) => {
- this.fruitList = res.data;
- });
- },
- //添加数据
- postData() {
- axios.post("http://127.0.0.1:3000/fruits", {
- fruit: this.fruit,
- }).then(this.getFruitList());
- },
- //删除数据
- del(index){
- axios.delete(`http://127.0.0.1:3000/fruits/${index}`).then(this.getFruitList())
- }
- },
- created() {
- this.getFruitList();
- },
- };
- script>
res用不了,不知道什么情况。就必须每次都手动刷新浏览器。
