2016-02-22 6 views
2

Я создаю небольшое клиентское приложение, которое развертывается на веб-сайте, построенном с помощью WYSIWYG CMS. (К сожалению, у меня нет доступа к серверу).Сгенерировать TinyURL с клиентской стороны JavaScript - требуется обход CORS

Я сохраняю состояние приложения в URL-адресе с хэш-бэгом и хотел бы сократить его, используя что-то вроде API-интерфейса TinyURL. По сути, я хотел бы запросить стороннюю службу с моим длинным URL-адресом в качестве запроса и получить ответ с сокращенным.

Моя проблема заключается в том, что я не знаю, как сделать это без ПОЛУЧАТЬ сообщение об ошибке CORS: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.site-im-working-on.com' is therefore not allowed access.

Вот пример того, что я пытался сделать (с помощью JQuery):

Есть ли способ обойти CORS, используя только клиентский код?

(Я также открыт для использования другого URL Shortener со свободным API.)

ответ

2

Поскольку вы заявили, вы открыты с помощью другого API, Google имеет JavaScript API, что позволяет укоротить URL, используя их URL-адрес goo.gl сокращен.

Я приспособил пример из Github ниже:

<!-- 
    Copyright (c) 2011 Google Inc. 
    Licensed under the Apache License, Version 2.0 (the "License"); you may not 
    use this file except in compliance with the License. You may obtain a copy of 
    the License at 
    http://www.apache.org/licenses/LICENSE-2.0 
    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
    License for the specific language governing permissions and limitations under 
    the License. 
    To run this sample, replace YOUR API KEY with your application's API key. 
    It can be found at https://code.google.com/apis/console/?api=plus under API Access. 
--> 
<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset='utf-8' /> 
    <style> 
     #info { 
     border: 1px solid black; 
     padding: 0.25em; 
     } 
    </style> 
    <script> 
     // Enter the API key from the Google Develoepr Console - to handle any unauthenticated 
     // requests in the code. 
     // The provided key works for this sample only when run from 
     // https://google-api-javascript-client.googlecode.com/hg/samples/simpleRequest.html 
     // To use in your own application, replace this API key with your own. 
     var apiKey = 'YOUR_API_KEY_HERE'; 
     function load() { 
     gapi.client.setApiKey(apiKey); 
     gapi.client.load('urlshortener', 'v1', showInputs); 
     } 
     function showInputs() { 
     document.getElementById('requestFields').style.display = ''; 
     } 
     function makeRequest() { 
     function writeResponse(resp) { 
      var responseText; 
      if (resp.code && resp.data[0].debugInfo == 'QuotaState: BLOCKED') { 
      responseText = 'Invalid API key provided. Please replace the "apiKey" value with your own.'; 
      } else { 
      responseText = 'Short URL is: ' + resp.id; 
      } 
      var infoDiv = document.getElementById('info'); 
      infoDiv.innerHTML = ''; 
      infoDiv.appendChild(document.createTextNode(responseText)); 
     } 
     var longUrl = document.getElementById('longUrl').value; 
     var request = gapi.client.urlshortener.url.insert({ 
      'longUrl': longUrl 
     }); 
     request.execute(writeResponse); 
     } 
    </script> 
    <script src="https://apis.google.com/js/client.js?onload=load"></script> 
    </head> 
    <body> 
    <p>Enter a long URL and click "Shorten URL" to get the short URL.</p> 
    <div id="requestFields" style="display:none;"> 
     <label for="longUrl">Long URL </label> 
     <input id="longUrl" type="text" value="https://stackoverflow.com" /> 
     <button onclick="makeRequest();"> 
     Shorten URL 
     </button> 
    </div> 
    <div style="margin-top:0.5em;"><span id="info">Results</span></div> 
    </body> 
</html> 

Чтобы использовать код выше вам нужно получить ключ API от Google Developers Console

+0

Это выглядит многообещающим. Я попытаюсь отредактировать скрипт, чтобы захватить window.location.href и посмотреть, смогу ли я заставить его работать. – coffeecola

+0

Это сработало. Спасибо, @aidanharris! – coffeecola