无法从React axios帖子接收Web API HttpPost方法中的数据 [英] Unable to receive data in a Web API HttpPost method from React axios post

查看:113
本文介绍了无法从React axios帖子接收Web API HttpPost方法中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web API Post方法可以在Swagger上正常工作,但是当我使用axios从我的React App发送一个发布请求时,数据[FromBody]为空.这是Web API方法.

My Web API Post method is working fine with Swagger, but when I send a post request from my React App with axios, the data [FromBody] is null. Here is the Web API method.

[HttpPost]
[Route("api/employee/addMany")]
public IHttpActionResult Post([FromBody] dynamic data)  //my axios request hit this method but data is always null. I have tried passing without stringifying
  {
   Employee[] employees=JObject.Parse(data);
   //doing some stuff with employees
   return Ok();
  }

这是Axios发布请求代码

And here is the Axios post request code


export function addEmployees(employees:Employee[]) {
  return axios.post(`api/employee/addMany`, { employees });
}

这是请求拦截器,它执行模型密钥Pascalization和Stringifying数据.

And here is the request interceptor, performing Model Keys Pascalization and Stringifying data.

const pascalizeKeys = (obj:any):any => {
  if (Array.isArray(obj)) {
    return obj.map(v => pascalizeKeys(v));
  } else if (obj !== null && obj.constructor === Object) {
    return Object.keys(obj).reduce(
      (result, key) => ({
        ...result,
        [String(upperFirst(key))]: pascalizeKeys(obj[key]),
      }),
      {},
    );
  }
  return obj;
};

export function applyInterceptors(Axios:typeof axios){
  Axios.interceptors.request.use((request)=>{
    if(request.data){
      request.data = JSON.stringify(pascalizeKeys(request.data));
      return request;
    }
    return request;
  }
  )
}

推荐答案

尝试使axios正常工作的方法:

Things to try to get axios post working:

  1. 设置标题

headers: {
          'content-type': 'application/json',
     }

  1. 尝试将json附加到请求的 data params 字段

如果仍然无法获取数据,请改为在数据字段中将其作为新的 formData 发送

If you still can't manage to get your data, send it as a new formData in the data field instead

let formData = new FormData()

formdata.append('name', yourJson)

await axios({
  method: 'post',
  url: '/your/url',
  data: formData,
  headers: {
    'Content-Type': 'multipart/form-data',
  },
})

,您应该立即收到请求

这篇关于无法从React axios帖子接收Web API HttpPost方法中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆