如何在 React 中进行 Axios POST 请求?

如何在 React 中进行 Axios POST 请求?

我们将制作一个 Axios POST 请求 创建数据或将数据插入数据库。我们将在 POST 请求中发送请求参数,并且还将举例发送 HTTP 标头。

在继续之前,请确保您的机器上安装了正确的反应应用程序并且工作正常。更多详情请查看 如何安装 react 和创建应用程序 .

从 NPM 安装 Axios

使用以下 npm 命令 安装 Axios 包 在你的项目中。确保您位于项目目录中。

 npm 安装 axios 或者 纱线添加axios

导入 axios 包的语法

 从“axios”导入axios;

React 中的 Axios HTTP POST 请求

让我们使用 基于函数的反应组件 使用 Axios 发出 POST 请求。

基于函数的组件也将创建一个 处理提交() 运行 Axios 请求的函数。

 导入反应,{ useState,useEffect } from 'react';  
 从'axios'导入axios; 函数 CreateEmployee() {  
 const [状态,setStatus] = useState('');  
 const [employee_name, setEmployeeName] = useState("");  
 const [employee_salary, setEmployeeSalary] = useState("");  
 const [employee_age, setEmployeeAge] = useState(""); 处理提交(){  
 axios.post(`[ http://dummy.restapiexample.com/api/v1/create`](http://dummy.restapiexample.com/api/v1/create%60) , {  
 员工姓名:{员工姓名},  
 employee_salary:{employee_salary},  
 雇员年龄:{雇员年龄}  
 })  
 .then(响应 => {  
 setStatus(response.status);  
 })  
 } 返回 (  
 <>  
 <h4>React 中的 Axios POST 请求示例</h4> <input type="text" name="employee_name" value={employee_name}/>  
 <input type="text" name="employee_salary" value={employee_salary}/>  
 <input type="number" name="employee_age" value={employee_age}/> <input type="button" name="submit" value="Submit" onClick={handleSubmit}/> {状态 && 状态}  
 </>  
 );  
 }

在上面的 react hook 示例中,我们使用 axios 在 处理提交() 函数并使用 useState 钩子将响应设置为状态。然后从状态返回成功消息作为回报。

带有 HTTP 标头的 Axios POST 请求

如果要发送带有请求的 HTTP 标头,则可以将第三个参数作为标头键和值的对象传递。

 处理提交 = () => {  
 常量 { 员工姓名,员工薪水,员工年龄 } = this.state;  
 常量头 = {  
 'Authorization': 'Bearer token_value',  
 };  
 axios.post(`[ http://dummy.restapiexample.com/api/v1/create`](http://dummy.restapiexample.com/api/v1/create%60) , {  
 员工姓名:{员工姓名},  
 employee_salary:{employee_salary},  
 雇员年龄:{雇员年龄}  
 }, { 标题 })  
 .then(响应 => {  
 this.setState({ 状态: response.status })  
 })  
 .catch(错误 => {  
 this.setState({ errorMessage: error.message });  
 });  
 }

在上面的示例中,我们为 header 对象创建了一个 const,然后将其作为第三个参数传递给 Axios POST 请求。如果您愿意,您还可以传递任何客户标头。

您也可以使用 Axios API 发送 post 请求,请参阅详细指南 Axios API 发布请求 .

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明

本文链接:https://www.qanswer.top/38144/27422011

posted @ 2022-09-20 11:28  哈哈哈来了啊啊啊  阅读(722)  评论(0编辑  收藏  举报