当前位置: 首页 > news >正文

vue3+koa+axios实现前后端通信

vue3+koa+axios实现前后端通信

写了一个小demo来实现前后端通信,涉及跨域问题,非常简单可以给大家平时开发的时候参考

服务端:
目录结构如下:
在这里插入图片描述
router index.js


// router的入口文件
// 引入路由
const Router = require("koa-router")
const router = new Router()
router.get("/", async (ctx) => {ctx.body = "首页"})router.get("/list",async(ctx)=>{ctx.body={data:[{name:1},{name:2}]}})
// router.use()
router.use(router.routes(), router.allowedMethods())// 一般首页是直接访问ip+端口号进入,所以可以将期重定向到/home下的某一个路由
router.redirect("/", "/list")module.exports = router // 导出router给app.js使用

app.js

// 整个koa项目的入口文件
const Koa = require("koa") // 引入koa
const app = new Koa() // 声明一个实例
const port = 3000 // 端口号
const router = require("./router/index") // 配置路由
const cors = require("koa-cors") // 解决跨域
const static = require("koa-static") // 静态资源管理
const path = require("path")/*** use()就是调用router中间件* router.routes()作用是启动路由* router.allowedMethods()作用是允许任何请求(例如:get,post,put)*/
//  router.get("/list",async(ctx)=>{
//     console.log(ctx)
//     ctx.body={
//         data:[{name:1},{name:2}]
//     }// })
app.use(static(path.join(__dirname + "/public"))) //读取静态资源
app.use(cors({exposeHeaders: ['WWW-Authenticate', 'Server-Authorization', 'x-show-msg'],maxAge: 5,  //  该字段可选,用来指定本次预检请求的有效期,单位为秒allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 允许的请求方法allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With'] 
})) //后端允许跨域访问app.use(router.routes(), router.allowedMethods())app.listen(port, () => {console.log(`server in running at http://localhost:${port}`)
})

前端:
首先要安装axios
main.js

import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'const app = createApp(App)
app.config.globalProperties.$axios = axios
app.mount('#app')

vue.config.js

module.exports = {devServer: {port:8080,open:true,proxy: {'/api': {target: 'http://localhost:3000/', //接口域名changeOrigin: true,             //是否跨域ws: true,                       //是否代理 websocketssecure: false,                   //是否https接口pathRewrite: {                  //路径重置'^/api': ''}}}}
};

前端请求数据:

<template><div class="hello"><button @click="sendMessage">click me</button>  <input type="text" :value="msg"></div>
</template><script src="./hello"></script><!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
import axios from "axios"
import {ref} from 'vue'export default {setup(){let msg=ref();function sendMessage(){axios.get('/api/list').then(function(res){console.log(res.data.data)msg.value=res.data.data[0].name})}return{msg,sendMessage}}
http://www.lryc.cn/news/198860.html

相关文章:

  • Required MultipartFile parameter ‘file‘ is not present
  • vue3后台管理系统之layout组件的搭建
  • Minio 文件上传(后端处理同文件判断,同一文件秒传)
  • 模拟IIC通讯协议(stm32)(硬件iic后面在补)
  • 使用注解读取properties配置文件
  • Python---练习:求世界杯小组赛的总成绩(涉及:布尔类型转换为整型)
  • vue3学习源码笔记(小白入门系列)------KeepAlive 原理
  • 边写代码边学习之mlflow
  • 基于吉萨金字塔建造优化的BP神经网络(分类应用) - 附代码
  • axios的post请求所有传参方式
  • 【c++】向webrtc学比较2: IsNewerSequenceNumber 用于NackTracker及测试
  • PRCV 2023:语言模型与视觉生态如何协同?合合信息瞄准“多模态”技术
  • 深度学习硬件配置推荐(kaggle学习)
  • 1019hw
  • 两分钟搞懂UiAutomator自动化测试框架
  • Fast DDS之Subscriber
  • 测试PySpark
  • C语言- 原子操作
  • 设置hadoop+安装java环境
  • 阿里云新加坡主机服务器选择
  • 21天打卡掌握java基础操作
  • SQL题目记录
  • Linux程序调试器——gdb的使用
  • 前端打包项目上线-nginx
  • 创龙瑞芯微RK3568参数修改(调试口波特率和rootfs文件)
  • VMware——VMware17安装WindowServer2012R2环境(图解版)
  • ModuleNotFoundError: No module named ‘torch‘
  • 采用Spring Boot框架开发的医院预约挂号系统3e3g0+vue+java
  • Jmeter性能测试(压力测试)
  • NetCore/Net8下使用Redis的分布式锁实现秒杀功能