Answer the question
In order to leave comments, you need to log in
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 );
}
Answer the question
In order to leave comments, you need to log in
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 "
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question