How to achieve interaction between front-end and back-end in Axios?
To achieve interaction between the front-end and back-end, you can utilize axios to send HTTP requests and receive responses.
In the frontend, you can use the following code to send a request:
import axios from 'axios';
axios.get('/api/data') // 发送GET请求
.then(response => {
console.log(response.data); // 处理响应数据
})
.catch(error => {
console.error(error); // 处理错误
});
axios.post('/api/data', { name: 'John', age: 25 }) // 发送POST请求
.then(response => {
console.log(response.data); // 处理响应数据
})
.catch(error => {
console.error(error); // 处理错误
});
In the backend, you can use the following code to handle requests and send responses:
const express = require('express');
const app = express();
app.get('/api/data', (req, res) => { // 处理GET请求
res.send({ message: 'Hello World!' }); // 发送响应数据
});
app.post('/api/data', (req, res) => { // 处理POST请求
const { name, age } = req.body; // 获取请求体中的数据
// 处理数据
res.send({ message: `Hello ${name}, you are ${age} years old!` }); // 发送响应数据
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
The code above utilizes the Express framework to create a basic server. Different routes are defined using app.get and app.post methods, and response data is sent using the res.send method.
In the axios request on the frontend, the URL needs to be adjusted according to the actual circumstances to match the routing settings on the backend server.