在 Jquery Ajax POST 中出现 400 个错误的请求错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16017081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:12:30  来源:igfitidea点击:

Getting 400 bad request error in Jquery Ajax POST

jqueryajaxposthttp-status-code-400

提问by sachinjain024

I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.

我正在尝试使用 Jquery 发送 Ajax POST 请求,但出现 400 个错误的请求错误。

Here is my code:

这是我的代码:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: {
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  },
  error: function(e) {
    console.log(e);
  }
});

It Says: Can not build resource from request. What am I missing ?

它说:无法根据请求构建资源。我错过了什么?

回答by sachinjain024

Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:

最后,我犯了错误,原因是我需要对我发送的 JSON 数据进行字符串化。我必须在 XHR 对象中设置内容类型和数据类型。所以正确的版本在这里:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: JSON.stringify({
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  }),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

May be it will help someone else.

也许它会帮助别人。

回答by Dulith De Costa

Yes. You need to stringifythe JSONdata orlse 400 bad requesterror occurs as it cannot identify the data.

是的。你需要stringifyJSONorlse数据400 bad request,因为它不能识别数据发生错误。

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

错误的请求。您的浏览器发送了此服务器无法理解的请求。

Plus you need to add content typeand datatypeas well. If not you will encounter 415error which says Unsupported Media Type.

另外,您还需要添加content typedatatype。如果不是,你会遇到415错误,上面写着Unsupported Media Type

415 Unsupported Media Type

415 不支持的媒体类型

Try this.

尝试这个。

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

通过这种方式,您可以轻松修改所需的数据。它不会让您感到困惑,因为它是在 ajax 块之外定义的。

回答by Beno?t Schiex

The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.

这个问题有点老了……但以防万一有人面临错误 400,也可能来自需要将 csrfToken 作为参数发布到发布请求。

You have to get name and value from craft in your template :

您必须从模板中的工艺中获取名称和值:

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>

and pass them in your request

并在您的请求中传递它们

data: window.csrfTokenName+"="+window.csrfTokenValue

回答by Norbert Norbertson

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

以防其他人遇到这种情况。我有一个在桌面浏览器上运行良好的网站,但我在 Android 设备上遇到了 400 个错误。

It turned out to be the anti forgery token.

原来是防伪令牌。

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

问题是 .Net 控制器设置不正确。

I needed to add the attributes to the controller:

我需要将属性添加到控制器:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

代码需要,但至少现在我知道是什么导致了它。400 错误根本没有帮助。

回答by Christian Ezeani

You need to build query from "data" object using the following function

您需要使用以下函数从“数据”对象构建查询

function buildQuery(obj) {
        var Result= '';
        if(typeof(obj)== 'object') {
            jQuery.each(obj, function(key, value) {
                Result+= (Result) ? '&' : '';
                if(typeof(value)== 'object' && value.length) {
                    for(var i=0; i<value.length; i++) {
                        Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
                    }
                } else {
                    Result+= [key, encodeURIComponent(value)].join('=');
                }
            });
        }
        return Result;
    }

and then proceed with

然后继续

var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: buildQuery(data),
  error: function(e) {
    console.log(e);
  }
});