Neither can I deal with CORS.

There is such a simple code:

function loadUserInfo(userId) { var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.vkontakte.ru/method/users.get?version=5.57&user_ids=' + userId, false); xhr.withCredentials = true; xhr.send(); if (xhr.status != 200) { return false; } else { return JSON.parse(xhr.responseText).response.shift(); } } 

With it, I want to get information about the newly logged in user. Constantly crashes:

vk.html: 37 XMLHttpRequest cannot load https://api.vkontakte.ru/method/users.get?version=5.57&user_ids=209295007 . No 'Access-Control-Allow-Origin' header is present. Origin ' http://mysite.ru ' is not allowed access.

I checked the base domains in the VC application, added withCredentials = true , but all this does not solve the problem.

  • 3
    It is necessary to send via jsonp protocol. withCredentials = true will not help ...... Either use openAPI - Alexey Shimansky

1 answer 1

On the advice of Alexey, I released everything using the JSONP protocol:

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <script> window.onload = function() { var callbackResponse = (document.URL).split("#")[1]; var responseParameters = (callbackResponse).split("&"); var parameterMap = []; for (var i = 0; i < responseParameters.length; i++) { parameterMap[responseParameters[i].split("=")[0]] = responseParameters[i].split("=")[1]; } if (parameterMap.access_token !== undefined && parameterMap.access_token !== null) { jsonp('https://api.vkontakte.ru/method/users.get?version=5.57&user_ids=' + parameterMap.user_id, function(userInfo) { userInfo = userInfo.response[0]; console.log(userInfo); }); } else { alert("Ошибка авторизации в ВК"); } function jsonp(url, callback) { var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random()); window[callbackName] = function(data) { delete window[callbackName]; document.body.removeChild(script); callback(data); }; var script = document.createElement('script'); script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName; document.body.appendChild(script); } } </script> </head> <body> <h1>Redirecting...</h1> </body> </html>