I want to store data via POST method using react axios into table via ASP .net. The API works on postman but the data Im sending on the frontend side shows null on the backend POST method.
React code:
var headers = {
'Authorization': 'Bearer ' + localStorage.getItem('tk'),
'Content-Type': 'application/json'
}
axios.post("https://localhost:8000/api/" + 'Author',
{
Data: this.state.books, //"Book1 (string)"
Text: this.state.text, //"Douglas M (string)"
List: [1,2,3] //array
}, {headers: headers})
.then((response) => {
window.location.href = '/home';
})
.catch((error) => {
console.log(error);
});
C# code:
[Produces("application/json")]
[HttpPost]
public HttpResponseMessage Post([FromBody] Author value)
{
Author input = new Author ()
{
Data = value.Data,
Text = value.Text,
Lis = value.List,
Date = Datetime.now
};
_model.Author.Add(input);
_model.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
Author model design:
public class Author
{
public string Data { get; set; }
public string Text { get; set; }
public string Lis { get; set; } //storing list as string in table
}
Error returned:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
When the API is executed, the value that the POST method retrieves is NULL. What's the reason for this? I tried using JSON.stringify() for the data in frontend but it didnt work.
JSON.stringify()and your modelAuthorand its properties (name and type) from server need to match exactly the object sent from client.console.log(this.state.books)to check if the two value you pass actually have the value? And how is the two properties type, simple string? Pls share the model design ofAuthorand also pls share what is the data you post.string ListtoList<int> List. The other way is that you can change[1,2,3]to"[1,2,3]".