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

本地学习axios源码-如何在本地打印axios里面的信息

1. 下载axios到本地

git clone https://github.com/axios/axios.git

2. 下载react项目, 用vite按照提示命令配置一下vite + react + ts项目

npm create vite my-vue-app --template react

3. 下载koa, 搭建一个axios请求地址的服务端

a.初始化package.json

mkdir koa-server
cd koa-server
npm init -y

 b.安装koa以及一些必要的中间件

npm install koa koa-router koa-bodyparser @koa/cors

c.创建服务器,在项目根目录下创建一个 server.js 文件

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors');const app = new Koa();
const router = new Router();// 使用中间件
app.use(cors());
app.use(bodyParser());// 定义路由
router.get('/api/data', async (ctx) => {ctx.body = { message: 'Hello from Koa!' };
});router.post('/api/data', async (ctx) => {const data = ctx.request.body;ctx.body = { received: data };
});// 使用路由
app.use(router.routes()).use(router.allowedMethods());// 启动服务器
const port = 3009;
app.listen(port, () => {console.log(`Koa server is running on http://localhost:${port}`);
});

d.启动koa服务器 

node server.js

 4. 把本地的axios引入到react项目中

import React, { useEffect, useState } from 'react';import axios from '../../axios/lib/axios';console.log('axios:::', axios);export default function Home() {const [message, setMessage] = useState<string>('');const [postData, setPostData] = useState<any>(null);useEffect(() => {// GET 请求axios.get('http://localhost:3009/api/data').then((response: any) => {console.log('response:::', response);setMessage(response.data.message);}).catch((error: any) => {console.error('Error fetching data:', error);});}, []);const handlePost = () => {// POST 请求axios.post('http://localhost:3009/api/data', { data: 'Hello from React!' }).then((response: any) => {console.log('response:::', response);setPostData(response.data.received);}).catch((error: any) => {console.error('Error posting data:', error);});};return (<div className="App"><h1>{message}</h1><button onClick={handlePost}>Send POST Request</button>{postData && <p>Received: {postData.data}</p>}</div>)
}

 就可以在axios文件中console打印日志了

 

http://www.lryc.cn/news/494797.html

相关文章:

  • 1、SpringBoo中Mybatis多数据源动态切换
  • 【浏览器】缓存与存储
  • 积鼎科技携手西北工业大学动力与能源学院共建复杂多相流仿真联合实验室
  • 5. langgraph实现高级RAG (Adaptive RAG)
  • Postman设置接口关联,实现参数化
  • 代码随想录day02--链表
  • 杰发科技AC7803——不同晶振频率时钟的配置
  • ArcGIS栅格影像裁剪工具
  • 【查询目录】.NET开源 ORM 框架 SqlSugar 系列
  • docker快速安装zookeeper
  • MySQL中如何减少回表
  • 初始Python篇(7)—— 正则表达式
  • 洛谷P1443 马的遍历
  • 代理IP地址的含义与设置指南‌
  • Vue--------导航守卫(全局,组件,路由独享)
  • ElasticSearch7.x入门教程之全文搜索(七)
  • Adversarial Learning forSemi-Supervised Semantic Segmentation
  • UCOS-II 自学笔记
  • C++ - 二叉搜索树讲解
  • 基于开源云原生数据仓库 ByConity 体验多种数据分析场景
  • RabbitMQ 消息确认机制
  • Node.js:开发和生产之间的区别
  • 【QT】背景,安装和介绍
  • 从0到1搭建webpack
  • 针对解决conda环境BUG的个人笔记
  • 读《Effective Java》笔记 - 条目13
  • SQL 之连接查询
  • vscode切换anaconda虚拟环境解释器不成功
  • 一个实用的 Maven localRepository 工具
  • 目标检测,图像分割,超分辨率重建