M
M
Millerish2017-12-19 12:43:38
JavaScript
Millerish, 2017-12-19 12:43:38

JS: How to send a message to VK?

Hey!
I need to send a message to a VK user on behalf of the community. Found different implementations, but gives an error:

Failed to load https://api.vk.com/method/messages.send: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' XXXX.ru ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

let token = 'XXXX';
        let user_id = 99999;
        let message = 'msg';
        let apiMsg = 'https://api.vk.com/method/messages.send';

        let header = new Headers({
            'Access-Control-Allow-Origin':'*',
            'Content-Type': 'multipart/form-data'
        })

        let data = {
            'user_id': user_id,
            'message': message,
            'access_token': token
        };

        let options = {
            mode: 'cors',
            header: header,
            'method': 'post',
            'payload': data
        };

        fetch(apiMsg, options)
            .then((data) => {
                return data.text()
            })
            .then((text) => {
                console.log(text)
            })
            .catch((error) => {
                console.log('There has been a problem with your fetch operation: ' + error.message)
            })

Why does the error occur, I finished off Access-Control-Allow-Origin? How right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Filippov, 2017-12-19
@Millerish

'Access-Control-Allow-Origin':'*',

as far as I understand, this header should be registered on the server, and not sent in the request, that is, you do not need to use cors, as indicated in the error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question