Я не могу позвонить в Google с помощью Javascript/Heroku CORS нигде или Node

Мне нужно использовать ограниченное устройство ввода Google для входа с кодом на экране. Это недоступно для веб-приложений, поэтому я должен использовать тип Other, поэтому я не могу установить CORS, поэтому я настроил прокси на Heroku, используя это.

Это отлично работает:

curl https://xxxxx.herokuapp.com/https://accounts.google.com/o/oauth2/device/code -H "x-requested-with: *" -d "client_id=xxxxx.apps.googleusercontent.com&scope=profile"

Это возвращает и ошибка: invalid_request

var xhr = new XMLHttpRequest();
xhr.onload = function() {
  console.log(this.responseText);
  var data = JSON.parse(this.responseText);
  console.log(data);
}
xhr.open("POST", 'https://xxxxxxx.herokuapp.com/https://accounts.google.com/o/oauth2/device/code', true);
xhr.setRequestHeader('x-requested-with', '*');
xhr.send(JSON.stringify({
  client_id: 'xxxxxxxxxxxxxxxx.apps.googleusercontent.com',
  scope: 'profile'
}));

И так же это:

var querystring = require('querystring');
var request = require('request');

request({
    uri: 'https://xxxx.herokuapp.com/https://accounts.google.com/o/oauth2/device/code',
    body: querystring.stringify({
      client_id: 'xxxxxx.apps.googleusercontent.com',
      scope: 'profile'
    }),
    headers: {
      'x-requested-with': '*'
    },
    method: 'POST'},
    function (error, response, body) {
        console.log(error)
        console.log(response)
        console.log(body)
    }
);

Что я делаю неправильно?

1 ответ

Решение

Измените код для вашего запроса XHR следующим образом:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
  console.log(this.responseText);
  var data = JSON.parse(this.responseText);
  console.log(data);
}
xhr.open("POST", 'https://xxxxxxx.herokuapp.com/https://accounts.google.com/o/oauth2/device/code', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("client_id=xxxxx.apps.googleusercontent.com&scope=profile");

То есть отправить Content-Type: application/x-www-form-urlencoded заголовок запроса и тело запроса в формате client_id=xxxxx.apps.googleusercontent.com&scope=profile,

По крайней мере, это то, что вы должны сделать, если вы хотите подражать curl запрос показан в вопросе - потому что curl вызов вызывает буквальное значение аргумента для -d возможность отправки в качестве тела запроса - client_id=xxxxx.apps.googleusercontent.com&scope=profile - с Content-Type: application/x-www-form-urlencoded заголовок запроса.

Вы можете подтвердить это самостоятельно, добавив --trace-ascii /dev/stdout к curl вызов и изучение следа, который curl логи в консоль.

Напротив, код для запроса XHR в вопросе "как есть" отправляет тело запроса в формате {client_id: "xxxxxxxxxxxxxxxx.apps.googleusercontent.com", scope: "profile"} с Content-Type: text/plain;charset=UTF-8 заголовок запроса.

См. Также раздел "Запрос устройства и пользовательских кодов" в соответствующей документации Google, где также отображается Content-Type: application/x-www-form-urlencoded Требуется заголовок запроса.

Другие вопросы по тегам