let assume, companyDetail is an object, and I have to pass list of company details to API. so can I d sent array of object in post request like this:- axios.post("",);
note API is made in ASP.NET Core Web API.
what type of data can we send ?
CodePudding user response:
You can send an array of objects as long as the endpoint expect to receive this type of data.
With axios:
const companyDetails = [
{ ... },
{ ... },
{ ... },
];
axios.post("https://myapi.com/companydetails", companyDetails)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
CodePudding user response:
Yes you can pass data as array of object companyDetail
but its depends on how API request body is created in backend. If API wants request body in some other custom variable lets as reqBody
the you have to assign your companyDetail
to reqBody
axios.post("endpoint", {reqBody: companyDetail})
If API wants request body in companyDetail
itself then:
axios.post("endpoint", {companyDetail})
CodePudding user response:
CompanyDetail is an object, and I have to pass list of company details to API. so can I d sent array of object in post request like this:- axios.post("",);Note API is made in ASP.NET Core Web API. What type of data can we send ?
Well, to begin with your first concern, yes we definitely can post list of object as axios.post("",)
fashion. Considering your scenario we can write that snippet as following:
Let's assume, we have model as below:
Model:
public class CompanyDetails
{
public int CompanyId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Asp.net core Web API:
[Route("api/[controller]")]
[ApiController]
public class AxiosWebApiController : ControllerBase
{
[HttpPost]
[Route("CompanyDetails")]
public async Task<IActionResult> CompanyDetails(List<CompanyDetails> companyDetails)
{
// Do whatever you like here
return Ok(companyDetails);
}
}
What type of data can we send ?
Well, its up to you, if your controller accept list of object as Model just like this List<CompanyDetails> companyDetails
then you can do as following.
Axios Request:
@section Scripts
{
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const CompanyId = "CompnayId:";
const Name = "Name:";
const Email = "Email:";
const companyDetails = [];
for (let i = 1; i <= 10; i ) {
const companyObject = {
CompanyId: CompanyId i,
Name: Name i,
Email: Email i
}
companyDetails.push(companyObject);
}
console.log(companyDetails);
axios.post("http://localhost:5094/api/AxiosWebApi/CompanyDetails", companyDetails);
</script>
}
Note: If your controller accept [FromForm]
then append as FormData()
just like formData.append("CompanyId", 1);
then push to your array object.
In addition, please check your browser console if the object posted accordingly as following:
Output: