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

news/2024/7/9 23:41:48 标签: vue, node.js

vue3koaaxios_0">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,                       //是否代理 websockets
                secure: 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.niftyadmin.cn/n/5100538.html

相关文章

vue.use和vue.prototype的区别

Vue.use(插件)和Vue.prototype下注册方法有以下主要区别: 注册范围: Vue.use注册的方法是全局的,所有Vue实例和组件都可以访问。 Vue.prototype注册的方法只作用于Vue实例,组件实例无法访问。 注册时机: Vue.use在main.js初始化Vue时调用,一经注册就生效。 Vue.prototype在…

Matlab2022b软件如何切换中/英文界面?

在中文Windows操作系统中&#xff0c;MATLAB2015b之后版本安装默认为中文版&#xff0c;但有部分用户还是习惯使用英文界面下的MATLAB&#xff08;个人偏好&#xff09;&#xff0c;下面以R2022b版分享一下中/英文界面的切换方法&#xff0c;超简单。 一、中文切换为英文界面&…

购药不烦恼:线上购药小程序的快捷方式

在这个数字化时代&#xff0c;线上购药小程序的快捷方式正在改变着我们购药的方式。本文将介绍如何通过使用Python和Flask框架创建一个简单的线上购药小程序的原型&#xff0c;为用户提供购药的便利和快捷体验。 安装和设置 首先&#xff0c;确保你已经安装了Python和Flask。…

C++11 decltype 的简单使用

decltype 是一个 C11 关键字&#xff0c;用于在编译时获取表达式的类型&#xff0c;而不实际计算表达式的值。它通常用于以下几个方面&#xff1a; 类型推导&#xff1a;可以获取表达式的类型。这对于泛型编程、模板编程非常有用int x 22; decltype(x) y; // y的类型为int函数…

【学习记录】动态数组(vector)的基本操作,包括插入、删除、扩容、输出、释放内存等。用C语言编写

#include <iostream> #include<cstdlib> #include<ctime> using namespace std;// 我的代码所犯的错误记录&#xff1a; // 1. \n的换行打成了/n导致程序迟迟不能换行 // 2. rand()%4&#xff0c;是随机0~3的随机数&#xff0c;并不是0~4 // 3. 在main主函数…

重塑消费者与商家关系的力量

在当前的商业模式中&#xff0c;消费者和商家之间往往存在着信息不对称和市场地位不对等的情况。消费者在购买商品或服务时&#xff0c;往往缺乏足够的激励机制&#xff0c;导致商家无法有效吸引和留住消费者。为了解决这一问题&#xff0c;一种新型的返利模式——排队返利模式…

Apache Shiro 组件反序列化漏洞分析

概述 Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。 它的原理比较简单&#xff1a;为了让浏览器或服务器重启后用户不丢失…

硬盘的简单介绍

硬盘的简单介绍 硬盘是服务器托管用户主机主要的数据存储介质。目前硬盘的种类有三类&#xff0c;不同的选择方案也会有不同的优劣对比。下面讲讲他们之间有什么不同吧 固态硬盘&#xff1a;  用固态电子存储芯片阵列而制成的硬盘&#xff0c;由控制单元和存储单元组成。固态…