ValuesController.cs (一部抜粋)
[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // POST api/values [HttpPost] public void Post([FromBody] string id) { } }
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <input type="button" value="click" onclick="get()" /> <input type="button" value="post" onclick="post()" /> <script> function get(){ var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function () { if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { console.log("GET: 通信成功"); } else { console.log("GET: 通信失敗"); } } }; httpRequest.onload = function () { console.log("GET: 通信完了"); }; httpRequest.open("GET", "api/values", true); httpRequest.send(null); } function post() { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function () { if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { console.log("POST: 通信成功"); } else { console.log("POST: 通信失敗"); } } }; httpRequest.onload = function () { console.log("POST: 通信完了"); }; httpRequest.open("POST", "api/values", true); httpRequest.setRequestHeader('Content-Type', 'application/json'); httpRequest.send(JSON.stringify("id=abc")); } </script> </body> </html>
POST を行うときには、setRequestHeader で Content-Type に application/json を指定する必要があります。ここが分からなくてしばらく調べました。
0 件のコメント:
コメントを投稿