本小节为设置跨域和axios请求和获取数据
设置跨域,在vue.config.js添加devServer配置
const { defineConfig } = require("@vue/cli-service"); module.exports = defineConfig({ transpileDependencies: true, devServer: { proxy: { "/api": { target: "https://localhost:7107/api/", //服务器请求地址 secure: false, //如果是https接口,需要配置这个参数 changeOrigin: true, //请求头host属性,false表示不修改,发真实本机过去,true表示修改,修改为服务器地址,会把host成target pathRewrite: { "^/api": "", }, }, }, }, });
备注:同源策略,协议相同,域名相同,端口相同
引入axios
npm install axios
src下新建api文件夹,api文件夹下新建api_config.js
import axios from "axios"; axios.defaults.baseURL = "http://localhost:8080/api"; axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest"; axios.defaults.headers.post["Content-Type"] = "application/json"; export default axios;
src下的components文件夹新建AddCategory.vue
<template> <el-dialog v-model="state.dialogVisible" title="Tips" width="500" :before-close="handleClose"> <span>This is a message</span> <template #footer> <div class="dialog-footer"> <el-button @click="dialogVisible = false">Cancel</el-button> <el-button type="primary" @click="dialogVisible = false"> Confirm </el-button> </div> </template> </el-dialog> </template> <script setup> import { reactive } from 'vue' const state = reactive({ dialogVisible: true }) </script>
src下router的index.js添加新页面的路由
{ path: "/addCategory", name: "addCategory", component: () => import("../components/AddCategory.vue"), },
标签:axios,api,VUE,笔记,学习,vue,defaults,import,true From: https://www.cnblogs.com/Lvkang/p/18215419