【问题标题】:Converting cURL to jQuery AJAX [duplicate]将 cURL 转换为 jQuery AJAX [重复]
【发布时间】:2019-01-25 15:51:55
【问题描述】:

我正在尝试使用后端团队给我的 curl 使用 jQuery AJAX 进行 API 调用。

curl -X POST \
  https://example1.com/api/sms \
  -H 'Accept: application/json' \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 's: APP' \
  -d '{ 
   "mobile": "1110002222"
 }'

但它抛出了 403 禁止错误:

Invalid CORS request

这是托管在另一个域名(example2.com)上的代码:

data = {mobile: '0001112222' };
success = function(data) { console.log(data); };
headers = {s: 'APP'};
$.ajax({
	type: 'POST',
	url: 'https://example1.com/api/sms',
	data: data,
	success: success,
	dataType: 'json',
	headers: headers
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我做错了什么或错过了什么?

【问题讨论】:

  • Invalid CORS request - 这就是你需要研究的东西...... CORS......仅仅因为curl可以做某事,并不意味着浏览器可以......浏览器只能做交叉对允许跨源请求的服务器的源请求
  • 您是否尝试过使用 headers ={ 'Accept': 'application/json', 'Cache-Control': 'no-cache', 'Content-Type': 'application/ json', 's': 'APP'} ?
  • @Jean-ClaudeColette 同样的错误,但谢谢。

标签: javascript jquery ajax


【解决方案1】:

我已阅读您的问题,请尝试以下代码:

var settings = {
  "async": true,
  "url": "https://example1.com/api/sms",
  "method": "POST",
  "headers": {
    "Content-Type": "application/json",
    "s": "APP",
    "Cache-Control": "no-cache",
  },
  "processData": false,
  "data": "{\"mobile\": \"1110002222\"}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

对于这个请求:

curl -X POST \
  https://example1.com/api/sms \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 's: APP' \
  -d '{"mobile": "1110002222"}'

【讨论】:

  • CORS 问题不谈,这是一件值得指出的好事情。我确实认为JSON.stringify() 会更好,而且 jQuery 还为$.ajax() 提供了一个特定的contentType 选项。 crossDomain在这里也没用
  • 是的,我知道 jQuery 有 content-type 选项,但我想将 cURL 请求准确地映射到 jQuery AJAX。我同意你的观点,crossDomain 选项没有用,所以我删除了它。
  • 同样的错误。但是谢谢你。
猜你喜欢
  • 2016-12-31
  • 2018-02-16
  • 2013-12-07
  • 2016-10-08
  • 2016-07-18
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
相关资源
最近更新 更多