【问题标题】:Converting curl cmd to jQuery $.ajax()将 curl 命令转换为 jQuery $.ajax()
【发布时间】:2013-12-07 23:06:56
【问题描述】:

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

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

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

我尝试过这样的 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");
    }
});

我错过了什么?

【问题讨论】:

  • 除非 API 支持使用 CORS 的跨域请求,否则你不能!但是,您可以对服务器端进行 ajax 调用,然后让服务器执行 cURL 操作。
  • @adeneo 我正在使用不阻止跨域请求的自定义打包,假设这是同源,我该如何让它工作?

标签: jquery ajax curl basic-authentication


【解决方案1】:

默认情况下 $.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");
    }
});

【讨论】:

猜你喜欢
  • 2018-02-15
  • 2017-05-18
  • 2016-05-20
  • 2016-12-31
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
相关资源
最近更新 更多