A
A
ALexLancer2019-11-01 02:39:40
CORS
ALexLancer, 2019-11-01 02:39:40

How to do cross-domain AJAX via fetch?

I'm trying to send SMS via sms.ru.

sms.ru/sms/send?api_id=CB50D676-EA3F-25D5-D688-A1B110DD7D4F&to=79833013604&msg=Helloworld&json=1

I deliberately inserted the left key. If you type in the browser line, then we get a JSON response. I'm trying to do the same with AJAX. SMS is sent but can't get JSON response. I did this through fetch, which makes CORS requests. The request passes without errors, but returns an empty body. Please tell me where I can be wrong.

var data = {
  api_id : '2220D676-EA3F-25D5-D689-A1B110DD7D4F',
  to     : '79833013604',
  msg    : 'Message',
  json   : '1'
};

postData('https://sms.ru/sms/send?' + $.param(data), data )
  .then( data => console.log( data ))
  .catch( error => console.error(error));

function postData(url = '', data = {}) {
  return fetch(url, {
    method: 'GET',
    mode: 'no-cors',
    credentials: 'same-origin',
    headers: {
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    },
    redirect: 'follow', // manual, *follow, error
   })
   .then(response => response );
}


If I set cors to mode, I get the error
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Those. the resource does not support CORS, and you need to set 'no-cors'. Is it possible to get data from such a resource?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
uncletobe, 2019-11-01
@ALexLancer

The problem is that for security purposes, ajax does not support cross-domain requests. All of these: cors, header customization, etc. did not help at all when there was a similar problem. The only solution I found for myself is for qjuey: use jsonp (works, 100% tested). Those. in the request, specify the type of data to be sent, as jsonp (dataType: 'jsonp'). There is no native support for fetch and axios, but the authors suggest alternatives:
axios " https://github.com/axios/axios/blob/master/COOKBOO... "
fetch " https://www.npmjs.com/package/ fetch-jsonp "

P
Petr Sh, 2019-11-01
@kester

Maybe it's better to put a "layer" on the back, knock on him from the front and let him contact sms.ru already?
At the same time, hide your key (api_id) on the back and not shine it on the front.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question