将 curl cmd 转换为 jQuery $.ajax()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20155531/
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-27 01:00:47  来源:igfitidea点击:

Converting curl cmd to jQuery $.ajax()

jqueryajaxcurlbasic-authentication

提问by krisrak

I'm trying to make a api call with jquery ajax, I have curl working for the api, but my ajax is throwing HTTP 500

我正在尝试使用 jquery ajax 进行 api 调用,我有 curl 为 api 工作,但我的 ajax 正在抛出 HTTP 500

I have a curl command working that looks like this:

我有一个 curl 命令,看起来像这样:

curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api

I tried ajax like this, but it is not working:

我试过这样的ajax,但它不起作用:

$.ajax({
    url: "http://www.example.com/api",
    beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: {foo:"bar"},
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});

What am I missing ?

我错过了什么?

回答by krisrak

By default $.ajax() will convert datato a query string, if not already a string, since datahere is an object, change the datato a string and then set processData: false, so that it is not converted to query string.

默认情况下 $.ajax() 将转换data为查询字符串,如果还不是字符串,因为data这里是一个对象,将 更改data为字符串然后设置processData: false,这样它就不会转换为查询字符串。

$.ajax({
    url: "http://www.example.com/api",
    beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    data: '{"foo":"bar"}',
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});