D
D
Dmitry2016-03-14 16:52:00
JavaScript
Dmitry, 2016-03-14 16:52:00

How to make a request to the vk server in javascript?

I'm trying to use an elementary way to make a request and get a response (XMLHttpRequest) without introducing VK.Api methods into the code, but I don't get the expected response - json strings. However, if you go to the request address, the procedure is executed correctly and a json string with access_token="....." and expires_in="0" appears on the screen.
What is my problem?

var request= new XMLHttpRequest();
    request.open('GET','https://oauth.vk.com/access_token?client_id=********&client_secret=********&v=5.50&grant_type=client_credentials',false);
    request.send();
    alert(request.responseText);


Here's how to make a request

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mark Doe, 2016-03-14
@Papa_kfc

Your problem is that the same-origin policy prevents you from making the request. It is better to either make such requests from the server, or use JSONP and / or other workarounds.

A
Alexander Shvaikin, 2016-03-14
@shurik_sh

I played around with Api only, and also tried XMLHttpRequest, but it turned out only with JSONP
, for example, this code:

$.ajax({
  url: 'https://api.vk.com/method/database.getCities?',
  data: {

    country_id: "1",
    q: "Санкт"
  },
  type: 'GET',
  dataType: 'jsonp',
  success: function(data) {
    console.log(data.response[0])
  }
})

M
Mikhail, 2016-03-14
@NeiroNext

Where are you trying to call this code from?
According to the security policy, this XMLHttpRequest call is possible only from the current domain, this is a JS security restriction, or both, but if the server gives a special header allowing this for your domain.
That is, it will work to call such a code from the console while on the VK page, but not on the other.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question