站长网站被跳转怎么办,购物型网站建设,公司网站域名实名认证怎么做,php 简单购物网站vue3koaaxios实现前后端通信
写了一个小demo来实现前后端通信,涉及跨域问题#xff0c;非常简单可以给大家平时开发的时候参考
服务端#xff1a; 目录结构如下#xff1a; router index.js // router的入口文件
// 引入路由
const Router require(koa-routerkoaaxios实现前后端通信
写了一个小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 axiosconst 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: }}}}
};
前端请求数据
templatediv classhellobutton clicksendMessageclick me/button input typetext :valuemsg/div
/templatescript src./hello/script!-- Add scoped attribute to limit CSS to this component only --
style scoped
/styleimport axios from axios
import {ref} from vueexport default {setup(){let msgref();function sendMessage(){axios.get(/api/list).then(function(res){console.log(res.data.data)msg.valueres.data.data[0].name})}return{msg,sendMessage}}