Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch POST ReactJs to Controller .Net Core

I have problem in Fetch POST to controller, an showing error like {"errors":{"":["Unexpected character encountered while parsing number: W. Path '', line 1, position 6."]},"title":"One or more validation errors occurred.","status":400,"traceId":"0HLOGKVEBUTKL:00000007"}. When I debbug too, in my controller it's not passing to controller.

This what I POST to

enter image description here enter image description here

I'm using ReactJs for client-side, and Net Core for server-side. Here my code snippet:

AddList.js

 fetch('api/SampleData/AddEmployee', {
   method: 'POST',
   headers: {
     'Accept': 'application/json; charset=utf-8',
     'Content-Type': 'application/json;charset=UTF-8'
   },
   body: data,
 }).then((response) => response.json())
 .then((responseJson) => {
   console.log('Success:', JSON.stringify(responseJson));
   this.props.history.push("/list-data");
 })
   .catch(error => console.error('Error:', error));

SampleDataController.cs

[HttpPost("[action]")]
public JsonResult AddEmployee(EmployeesViewModel employee)
{
}

starrup.cs

 app.UseMvc(routes =>
 {
   routes.MapRoute(
     name: "default",
     template: "{controller}/{action=Index}/{id?}");

   routes.MapRoute(
     name: "api",
     template: "api/{controller}/{action}/{id?}");
 });
like image 703
Stfvns Avatar asked Sep 23 '26 18:09

Stfvns


1 Answers

You dont need this config

   routes.MapRoute(
     name: "api",
     template: "api/{controller}/{action}/{id?}");

Instead use routing in your controller like this

[Route("api/[controller]/[action]")]
public class YourController : Controller
like image 166
Tony Ngo Avatar answered Sep 25 '26 07:09

Tony Ngo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!