本地学习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打印日志了