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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。