1

I'm trying to make an API call with jQuery AJAX using curl as given to me by the backend team.

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"
 }'

But it is throwing a 403 forbidden error:

Invalid CORS request

This is the code hosted on another domain name (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>

What am I doing wrong or missing?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Elaine Byene
  • 3,868
  • 12
  • 50
  • 96
  • 1
    `Invalid CORS request` - that's what you need to research ... CORS ... just because `curl` can do something, does not mean a browser can ... a browser can only make a cross origin request to a server that allows a cross origin request – Jaromanda X Aug 19 '18 at 06:36
  • Have you tried to complete the headers with headers ={ 'Accept': 'application/json', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', 's': 'APP'} ? – Jean-Claude Colette Aug 19 '18 at 06:46
  • @Jean-ClaudeColette Same error but thank you. – Elaine Byene Aug 19 '18 at 08:34

1 Answers1

1

I have read your question, try this code instead:

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

for this request:

curl -X POST \
  https://example1.com/api/sms \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 's: APP' \
  -d '{"mobile": "1110002222"}'
MahanTp
  • 744
  • 6
  • 16
  • CORS issues aside, this is a good thing to point out. I do think `JSON.stringify()` would be better though and jQuery also has a specific `contentType` option for `$.ajax()`. `crossDomain` is also useless here – Phil Aug 19 '18 at 06:43
  • 1
    Yeah I know that jQuery has the content-type option but I want to exactly map the cURL request to jQuery AJAX. I agree with you that crossDomain option is useless so I removed it. – MahanTp Aug 19 '18 at 06:45
  • Same error. But thank You. – Elaine Byene Aug 19 '18 at 08:32