首页 > 解决方案 > React axios - TypeError:无法读取未定义的属性'post'

问题描述

我正在尝试使用在我的反应应用程序中发出发布请求Axios,但我TypeError 每次都得到。这是我的代码:

submitHandler = (e) => {
        e.preventDefault();
        axios.post('https://jsonplaceholder.typicode.com/posts', this.state)
            .then(response => {
                console.log(response);
            })
            .catch(error =>{
                console.log('error');
            })
    }

这是我每次提交表单时得到的

这是我的进口:

import './Form.css';
import React, { Component } from 'react'
import axios from 'axios'

TypeError: Cannot read property 'post' of undefined

好像是axios的错误,我检查了很多次安装都没有发现问题出在哪里。有人能帮我吗? 这是我的问题的代码沙箱 提前谢谢。

标签: javascriptreactjsaxios

解决方案


我试过你的代码沙箱链接。

我做了一些改变,对我来说效果很好。

submitHandler = (e) => {
const reqBody = this.state;
e.preventDefault();
axios
  .post("https://jsonplaceholder.typicode.com/posts", { reqBody })
  .then((res) => console.log(res))
  .catch((err) => console.log(err));
}

在此处输入图像描述


推荐阅读