Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST Fetch .Net Core

question. I am having an issue when doing fetch post going to controller, fetch get is working fine, only the post the value is always null. But when I am using a postman it's working fine. Hope someone can help

//JS Side

var url = 'Test/SaveReportDetail';
var data = { username: 'example' };

fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(data), // data can be `string` or {object}!
    headers: {
        'Accept': 'application/json; charset=utf-8',
        'Content-Type': 'application/json;charset=UTF-8'
    }
}).then(res => res.json())
    .then(response => console.log('Success:', JSON.stringify(response)))
    .catch(error => console.error('Error:', error));

//Controller Side

 [HttpPost]
 public JsonResult SaveReportDetail(string username)
 {
      //var RepObject = JsonConvert.DeserializeObject<ReportTemplate>(reportTemplate);
      //return "t";

      return Json("b");
  }
like image 682
ping pong Avatar asked Sep 04 '25 03:09

ping pong


1 Answers

You need to always use [FromBody] for data from request body,besides above answer, if you only need to pass a string, you could pass the string directly instead of wrap in an object:

var url = 'Test/SaveReportDetail';
var username =  'example' ;

fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(username), 
    headers: {
        'Accept': 'application/json; charset=utf-8',
        'Content-Type': 'application/json;charset=UTF-8'
    }
}).then(res => res.json())
    .then(response => console.log('Success:', JSON.stringify(response)))
    .catch(error => console.error('Error:', error));

Action:

[HttpPost]
public JsonResult SaveReportDetail([FromBody]string username)
like image 91
Ryan Avatar answered Sep 05 '25 20:09

Ryan