axios + json-server用法演示

json-server可以在前端模拟服务器返回json格式数据,使用时需要全局安装json-server包

npm i -g json-server

使用时需要开启服务,需要在终端找到自己的json文件并且监视:

 json-server --watch db.json

在这里插入图片描述
然后就可以开始写代码了:

基础使用:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>

<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
        <button class="btn btn-success">发送PUT请求</button>
        <button class="btn btn-danger">发送DELETE请求</button>
    </div>

    <script>
        // 获取按钮
        const btns = document.querySelectorAll('button');

        // GET请求
        btns[0].onclick = () => {
            axios({
                // 请求类型
                method: 'GET',
                // URL
                url: 'http://localhost:3000/posts'
            }).then(response => {
                console.log(response);
            })
        }

        // POST请求
        btns[1].onclick = () => {
            axios({
                // 请求类型
                method: 'POST',
                // URL
                url: 'http://localhost:3000/comments',
                // 设置请求体
                data: {
                    id: 2,
                    title: "这是一个POST请求",
                    author: "eyes++"
                }
            }).then(response => {
                console.log(response);
            })
        }

        // PUT请求
        btns[2].onclick = () => {
            axios({
                // 请求类型
                method: 'PUT',
                // URL
                url: 'http://localhost:3000/comments/2',
                // 设置请求体
                data: {
                    id: 2,
                    title: "这是一个PUT请求",
                    author: "eyes"
                }
            }).then(response => {
                console.log(response);
            })
        }

        // delete请求
        btns[3].onclick = () => {
            axios({
                // 请求类型
                method: 'delete',
                // URL
                url: 'http://localhost:3000/comments/2',
            }).then(response => {
                console.log(response);
            })
        }
    </script>
</body>
</html>

axios的一些方法:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>

<body>
    <div class="container">
        <h2 class="page-header">其他方法</h2>
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
    </div>
    <script>
        // 获取按钮
        const btns = document.querySelectorAll('button');

        // 发送GET请求
        btns[0].onclick = () => {
            axios.request({
                method: 'GET',
                url: 'http://localhost:3000/comments'
            }).then(response => {
                console.log(response);
            })
        }

        // 发送POST请求
        btns[1].onclick = () => {
            axios.post(
                'http://localhost:3000/comments',
                {
                    "body": "这是一个POST请求",
                    "postId": 2
                }
            ).then(response => {
                console.log(response);
            })
        }
    </script>
</body>

</html>

更多内容大家可以前往我的个人博客浏览:eyes++的个人空间

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面我为你提供一个简单的示例代码: 首先,我们需要在项目中安装需要的依赖: ``` npm install vue@next vue-router@next vuex@next axios json-server --save npm install --save-dev typescript @types/node @types/vue @types/vue-router @types/vuex ``` 接下来,我们先创建一个 `api.ts` 文件来处理登录请求: ```typescript import axios from "axios"; export const login = (username: string, password: string) => axios.post("/api/login", { username, password }); ``` 然后在 `main.ts` 中初始化 `axios`: ```typescript import { createApp } from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import axios from "axios"; axios.defaults.baseURL = "http://localhost:3000"; createApp(App) .use(store) .use(router) .mount("#app"); ``` 接着,在 `store` 目录下创建一个 `auth.ts` 文件来管理用户登录状态: ```typescript import { Module } from "vuex"; import { login } from "../api"; interface AuthState { isLoggedIn: boolean; username: string; } const authModule: Module<AuthState, any> = { namespaced: true, state: { isLoggedIn: false, username: "", }, mutations: { login(state, username: string) { state.isLoggedIn = true; state.username = username; }, logout(state) { state.isLoggedIn = false; state.username = ""; }, }, actions: { async login({ commit }, { username, password }) { try { const response = await login(username, password); commit("login", response.data.username); } catch (error) { console.error(error); throw error; } }, logout({ commit }) { commit("logout"); }, }, }; export default authModule; ``` 最后,在 `views` 目录下创建一个 `Login.vue` 文件,用于用户登录: ```vue <template> <div> <form @submit.prevent="login"> <label> Username: <input type="text" v-model="username" /> </label> <label> Password: <input type="password" v-model="password" /> </label> <button type="submit">Submit</button> </form> </div> </template> <script lang="ts"> import { defineComponent } from "vue"; import { useStore } from "vuex"; export default defineComponent({ name: "Login", setup() { const store = useStore(); const username = ref(""); const password = ref(""); const login = async () => { try { await store.dispatch("auth/login", { username: username.value, password: password.value }); router.push("/"); } catch (error) { console.error(error); alert("Error logging in, please try again."); } }; return { username, password, login, }; }, }); </script> ``` 最后,在 `router` 目录下定义路由: ```typescript import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; import Login from "../views/Login.vue"; import { store } from "../store"; const routes = [ { path: "/", name: "Home", component: Home, meta: { requiresAuth: true, }, }, { path: "/login", name: "Login", component: Login, }, ]; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes, }); router.beforeEach((to, from, next) => { const requiresAuth = to.matched.some((record) => record.meta.requiresAuth); if (requiresAuth && !store.state.auth.isLoggedIn) { next("/login"); } else { next(); } }); export default router; ``` 现在,你可以通过访问 `/login` 路径来尝试进行登录了。如果登录成功,你将被重定向到 `/` 路径,否则会提示错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值