Reputation: 99
I have question about sending string value on axios post. I will provide code below for better understanding.
public async Task<IActionResult> Save(string Code, [FromBody]string notes)
{
------
}
so above it will get the data of string from FROMBODY
export const sendNote = async (Url, code, value) => {
let Config = {
headers: {
"Content-Type": "application/json",
},
};
try {
const { data } = await axios.post(
Url + code + "/Notes",
value,
Config
);
return { data: data };
} catch (error) {
return { data: error.message };
}
};
So as you can see on the code above, I am trying to send the value which is a string to the api call on C# but I get many different error like 400 or 415. I researched it on google and they mostly put it on the json format.
So end it like "TEST" instead of {data: "TEST"}
Thank you
Upvotes: 3
Views: 5885
Reputation: 1
Ok, an axios call like this:
var object = {
myInt: 123456,
myString: "ciao Mondo"
}
return await axios.post("/Test/testFromBody", object)
want a controller method in C# like this:
[HttpPost, Route("testFromBody")]
public async Task<ActionResult> testFromBody([FromBody] TestClass test)
{
return Ok();
}
where TestClass is specular to the object which we sent.
If we do an axios call like this:
var formPayload = new FormData();
formPayload.append("myInt", 134)
formPayload.append("myString", 'Ciao mondo')
return await axios.post("/Test/testFromForm", formPayload)
the controller looks like:
[HttpPost, Route("testFromForm")]
public async Task<ActionResult> testFromForm([FromForm] int myInt, string myString)
{
return Ok();
}
otherwhise
var foo = "ciao Mondo"
var bar = 2345
return await axios.post(`/Test/testFromQueryParemtri?myInt=${foo}&myString=${bar}`)
the C# method
[HttpPost, Route("testFromQueryParemtri")]
public async Task<ActionResult> testFromQueryParemtri([FromQuery] int myInt, string myString)
{
return Ok();
}
Upvotes: -1
Reputation: 823
I found a solution that works for me.
The problem is in Content-Type
header.
...
headers: { "Content-Type": "application/json-patch+json" },
data: JSON.stringify(data),
params,
...
I have the same controller's method. I checked which headers uses in Swagger
.
It started working only after these changes.
Upvotes: 5