问题描述
我的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:
- 设置标题
headers: {
'content-type': 'application/json',
}
-
尝试将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方法中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!