React 使用 Axios 发送 HTTP 请求 - 完整指南
在 React 中使用 Axios 发送 HTTP 请求,需要先安装 Axios 库。可以使用 npm 或 yarn 进行安装。
npm install axios
yarn add axios
在组件中导入 Axios 并发送请求。例如,发送 GET 请求:
import axios from 'axios';
class MyComponent extends React.Component {
componentDidMount() {
axios.get('http://example.com/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
}
render() {
return (
<div>
// ...
</div>
);
}
}
发送 POST 请求:
import axios from 'axios';
class MyComponent extends React.Component {
handleSubmit = event => {
event.preventDefault();
const data = {
name: 'John Doe',
email: 'john.doe@example.com'
};
axios.post('http://example.com/api/users', data)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" name="name" />
<input type="email" name="email" />
<button type="submit">Submit</button>
</form>
);
}
}
原文地址: https://www.cveoy.top/t/topic/mmx3 著作权归作者所有。请勿转载和采集!