关于postman中ContentType与js写法的对应关系

ContentType的常用类型的有以下两种:

  1. "ContentType":"application/json"
  2. "Content-Type":"application/x-www-form-urlencoded"

1. "ContentType":"application/json"的案例

postman的调用

image.png

js请求:

jquery写法

        var obj={
            "data": $("#username").val()+"#"+$("#phone").val()+"#"+$("#title").val()+"#"+$("#company").val(),
            "vkey": lastCode,
            "vcode":$("#vcode").val()
        }
        var submitObj=JSON.stringify(obj)
        $.ajax({
            type:"POST",
            data:submitObj,
            url:submitUrl,
            "contentType":"application/json",
            success:function (res) {
                console.log(res)
                if(res.result===true){
                    alert("发送成功!")
                }else {
                    if(res.errmsg==="VCode error"){
                        getVcode()
                        alert("验证码错误")
                        return;
                    }
                    alert("发送失败!")
                }
            },
            error:function (res) {
                console.log(res)
                alert("网络出错!")
            }
        })

解读:

  1. 使用contentType: 'application/json', 则data只能是json字符串,也就是要对对象格式化为字符串,通常使用 var newObj=JSON.stringify(obj)
  2. 如果未使用contentType: 'application/json',则data应该为json对象。
如何从postman反推js写法?

如上图所示,采用的是raw-text格式。说明data类型为json字符串。因此要 JSON.stringify(data),contentType: 'application/json'


2. x-www-form-urlencoded的案例

postman的调用

image.png

js的写法

angular的写法

注意:$scope.account为json对象

        $http({
                method:"POST",
                data:$scope.account,
                url:config.login,
                withCredentials: true,
                headers:{
                    "Content-Type":"application/x-www-form-urlencoded"
                },
                transformRequest:transformRequest
            }).then(function(){})

jquery的写法

                var data = {
                    username: username,
                    password: password,
                    rememberMe: rememberMe
                };
                $.ajax({
                    url: url,
                    contentType: 'application/x-www-form-urlencoded',
                    data: data,
                    type: 'post',
                    success: successHandler,
                    error: reset
                });

解读:

  1. 当contentType为x-www-form-urlencoded时,提交的数据应该是json对象。
  1. 在angular和在jquery中contentType的写法略有不同。
    angular需要写在headers中,而jquery可以直接作为属性名。
  2. angular中method:"post",jquery中type:"post"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容