M
M
Maxim2020-07-19 11:50:29
In contact with
Maxim, 2020-07-19 11:50:29

How to make a request from localhost to VK API?

Situation.
I am using create-react-app.
Created an application on VK, received a token.
Created both Standalone application and website. In the application settings, I registered the addresses of sites localhost: 3000 with and without a port.
I'm trying to make a request:

fetch(`https://api.vk.com/method/users.search?q=${name}&sort=0&count=10&fields=photo_200&v=5.89&access_token=token`);


Error in console

Access to fetch at ' https://api.vk.com/method/users.search?q=%D0%BC%D0... ' from origin ' localhost:3000 ' 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.


After reading about CORS, I understand that the header does not come from the VK server, the browser blocks such a cross-domain request.
Error when using mode to 'no-cors'
Uncaught (in promise) SyntaxError: Unexpected end of input

What can I do to make everything work? How does the server decide who to allow requests to?
Is it really impossible to make requests to VK during development?
I have already read all the links, questions, articles several times, including from this site. I urgently need to do a task, but I can not find a solution.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2020-07-19
@mironov_m

It helped to use this !

G
GlebHleb, 2021-02-02
@GlebHleb

As this documentation says :

no-cors - ... In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

To bypass CORS, use JSONP as described in the VK documentation :
var script = document.createElement('script');
script.src = "https://api.vk.com/method/getProfiles?uid=66748&access_token=533bacf...&callback=callbackFunc";
document.getElementsByTagName("head")[0].appendChild(script);
function callbackFunc(result) {
   console.log(result);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question