简体   繁体   English

在 Jquery Ajax POST 中获取 400 错误请求错误

[英]Getting 400 bad request error in Jquery Ajax POST

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 ?我错过了什么?

Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending.最后,我得到了错误,原因是我需要对发送的 JSON 数据进行字符串化。 I have to set the content type and datatype in XHR object.我必须在 XHR 对象中设置内容类型和数据类型。 So the correct version is here:所以正确的版本在这里:

$.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.也许它会帮助别人。

Yes.是的。 You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.您需要对JSON数据进行stringify ,否则会发生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 type and datatype as well.另外,您还需要添加content typedatatype If not you will encounter 415 error which says Unsupported Media Type .如果不是,您将遇到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 块之外定义的。

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 错误根本没有帮助。

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

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);
  }
});

I'm hoping this may be of use to those encountering 400 errors while using AJAX in Wordpress going forward.我希望这可能对那些在 Wordpress 中使用 AJAX 时遇到 400 错误的人有用。 Even though this question is many years old, the solutions provided have all been programmatic, and I'm sure many have stepped through their code to repeatedly find it's correct, yet continue to find it is not working.尽管这个问题已经存在很多年了,但提供的解决方案都是程序化的,我相信很多人已经通过他们的代码反复发现它是正确的,但仍然发现它不起作用。

I found dozens of results asking how to resolve "WP AJAX request returning 400 Bad Request" or "WP AJAX request returning 0" and nothing today worked.我发现几十个结果询问如何解决“WP AJAX 请求返回 400 错误请求”或“WP AJAX 请求返回 0”,但今天没有任何效果。

Googling "How do I fix 400 bad request on Wordpress?"谷歌搜索“如何在 Wordpress 上修复 400 个错误请求?” finally resulted in the answer appearing from https://wp-umbrella.com/troubleshooting/400-bad-request-error-on-wordpress/最终导致答案出现在https://wp-umbrella.com/troubleshooting/400-bad-request-error-on-wordpress/

Clear your Web Browser Cache and Cookies清除您的 Web 浏览器缓存和 Cookie

You may be surprised, but most 400 errors in WordPress can be fixed by clearing your browser's cache and cookies.您可能会感到惊讶,但 WordPress 中的大多数 400 错误都可以通过清除浏览器的缓存和 cookie 来修复。 Browser caches temporarily store images, scripts, and other parts of websites you visit to speed up your browsing experience.浏览器缓存会临时存储您访问的网站的图像、脚本和其他部分,以加快您的浏览体验。

Clearing both my cache and cookies saw the 400 Bad Request code disappear and results return AJAX results as expected.清除我的缓存和 cookie 后,400 Bad Request 代码消失了,结果按预期返回了 AJAX 结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM