weixin_33691700 2017-06-14 10:21 采纳率: 0%
浏览 327

使用fetch()API的POST对象

I'm trying to post some data using the fetch() api and I keep receiving a "400 - Bad Request" error. I don't have any problem using the jQuery's $.ajax() method and I'm wondering what am I doing wrong:

data

let obj = {
    id_user: 57,
    id_category: 60,
    note: 'test'
}

Using jQuery (working)

$.ajax({
    url: 'http://localhost:3001/api/devices',
    type: 'post',
    data: obj
}).fail(function( xhr, status, errorThrown ) {
    alert( "Sorry, there was a problem!" );
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
  })

Using fetch() (not working)

fetch('http://localhost:3001/api/devices', {
    method: 'post',
    body: JSON.stringify(obj)
}).then(function(response){
    console.log(response)
}).catch(function(error) {
    console.log(error)
})

Response

Response {type: "basic", url: "http://localhost:3001/api/devices", redirected: false, status: 400, ok: false…}

Am I missing something?

  • 写回答

1条回答 默认 最新

  • weixin_33734785 2017-06-14 18:19
    关注

    Here is how to use the fetch API:

    namespace WebApi.Controllers
    {
        public class obj
        {
            public int id_user { get; set; }
            public int id_category { get; set; }
            public string note { get; set; }
        }
    
        public class devicesController : ApiController
        {
            public string Post([FromBody]obj value)
            {
                //use newtonsoft json
                string json = JsonConvert.SerializeObject(value);
                return json;
            }
        }
    }
    

    View:

         @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index2</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#callAjax").click(function () {
                    let obj = {
                        id_user: 57,
                        id_category: 60,
                        note: 'test'
                    }
    
                    //this worked for me, FYI, I USE different port than you
                    //$.ajax({
                    //    url: 'http://localhost:53110/api/devices',
                    //    type: 'post',
                    //    data: obj
                    //}).done(function (data, textStatus, jqXHR) {
                    //    alert(data);
                    //}).fail(function (xhr, status, errorThrown) {
                    //    alert("Sorry, there was a problem!");
                    //    console.log("Error: " + errorThrown);
                    //    console.log("Status: " + status);
                    //    console.dir(xhr);
                    //})
    
                    //https://davidwalsh.name/fetch - does not work in ie11
                    //https://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc
                    fetch('http://localhost:53110/api/devices', {
                        //I HAD TO add this headers because 415 unsupported media type
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        method: 'post',
                        body: JSON.stringify(obj)
                    }).then(function (response) {
                        //alert(response)
                        //ADDED THIS https://developers.google.com/web/updates/2015/03/introduction-to-fetch
                        response.json().then(function (data) {
                            alert(data);
                        });
                    }).catch(function (error) {
                        alert(error)
                    })
                })
            })
        </script>
    </head>
    <body>
        <div>
            <input type="button" value="callAjax" id="callAjax" />
        </div>
    </body>
    </html>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵