javascript - 使用客户端 JavaScript 生成 TinyURL——需要 CORS 解决方法

标签 javascript request cors client-side tinyurl

我正在构建一个小型客户端应用程序,该应用程序部署在使用所见即所得 CMS 构建的网站上。 (不幸的是,我无法访问服务器)。

我正在使用 hash-bang 将应用程序的状态保存在 URL 中,并想使用类似 TinyURL 的创建 API 之类的东西来缩短它。本质上,我想以我的长 URL 作为请求来查询 3rd 方服务,并收到一个缩短的响应。

我的问题是,如果没有收到 CORS 错误消息,我不知道如何执行此操作: 请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问来源“http://www.site-im-working-on.com”。

这是我一直在尝试做的事情的一个例子(使用 jQuery):

    var tinyAPI = 'http://tinyurl.com/api-create.php?url=';

    function getTinyURL () {
      var longURL = window.location.href;
      var request = tinyAPI + longURL;

      return $.get( request, function (response) {
        return response;
      });
    }

    // get tiny URL when on user action
    $('.share-button').on('click', function () {
      var tinyURL = tinyURL();
      // insert string into DOM element
      // copy string to user's clipboard
      // etc... 
    });

有什么办法绕过CORS吗?仅使用客户端代码?

(我也愿意使用另一个带有免费 API 的 URL 缩短器。)

最佳答案

由于您已经声明您愿意使用其他 API,因此 Google 有一个 JavaScript API允许您使用他们的 goo.gl URL 缩短服务来缩短 URL。

我改编了 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>

要使用上述代码,您需要从 Google Developers Console 获取 API key

关于javascript - 使用客户端 JavaScript 生成 TinyURL——需要 CORS 解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544698/

相关文章:

php - 通过ajax分割输出值,

javascript - 使用网络录音机需要将音频保存到服务器

javascript - 无法编辑请求内的变量

javascript - 使用 CORS 处理另一个站点上的重新身份验证

javascript - JavaScript/HTML 中的待办事项列表

javascript - JSon 的问题

c# - 使用 Request.Files 并在不重新加载页面的情况下从 POST 更改为 GET?

javascript - request.pipe() 和大文件的 Node 问题,错误 : cannot create a string longer than 0x1fffffe8 characters

javascript - 对预检请求的 Angular 响应未通过访问控制检查

javascript - cookie 域上的点前缀阻止 CORS 请求