【问题标题】:Axios Post Method does not activate the Action in the BackEndAxios Post Method 没有激活BackEnd中的Action
【发布时间】:2019-09-11 15:26:02
【问题描述】:

我想从我的 React JS 前端向我的后端 ASP.NET Core Web API 发出一个发布请求,但是在使用 @axios@ 时它没有被触发。

我按照互联网上的一些说明进行 axios get/post 请求,但它似乎不起作用

handleRegistration = (event) => {
    event.preventDefault();

    const user = {
        email: this.state.email,
        firstName: this.state.firstName,
        lastName: this.state.lastName,
        password: this.state.password
    };

    axios.post('http://localhost:{somenumbershere}/api/values', { user })
        .then(res => {
            console.log(res);
            console.log(res.data);
        })
}

我正在创建一个用户,并希望将他作为一个对象发送到我的 Action 方法到 BackEnd,但它从未遇到断点。如您所见,我将 obj 发送到的 url,@api/values/5@ 是发送到后端 action 方法的示例路由。我已经用 HttpPost 装饰了 Action,但仍然没有。

【问题讨论】:

  • 你的后端端点是什么...这个网址无效?
  • 这是action方法中指定的端点-@// POST api/values [HttpPost] public void Post([FromBody]string value)@
  • 首先,确保调用了您的 handleRegistration() 方法。一旦你确定它被调用了,你应该通过在你的 Promise 链中添加一个 catch 块来捕获错误。当您收到错误消息时,我们可以解决问题。
  • 是的,好主意。原来是:错误:“请求失败,状态码为 400”

标签: reactjs asp.net-web-api asp.net-core axios


【解决方案1】:

您需要使用FormData 对象发送数据,如下所示:

var formData = new FormData();
formData.append('email', this.state.email);
formData.append('firstName', this.state.firstName);
formData.append('password', this.state.password);
formData.append('password', this.state.password);

更多详情请见FormData docin this question

【讨论】:

  • 它起作用了,但是,Action Method 中的参数值为 null。现在我必须弄清楚这一点:)
【解决方案2】:

删除将用户包裹在 axios.post(..., user) 中的 {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-13
    • 2018-09-09
    • 2021-06-04
    • 1970-01-01
    • 2017-10-03
    • 2016-03-02
    • 2021-11-10
    • 2019-12-22
    相关资源
    最近更新 更多