【问题标题】:eBay API CORS request using JavaScript returns undefined使用 JavaScript 的 eBay API CORS 请求返回未定义
【发布时间】:2019-02-20 16:05:23
【问题描述】:

我想使用 JavaScript 从eBay Sandbox 获取 JSON 数据

我尝试通过 CORS 请求获取它(因为它是跨域请求),但它返回未定义。我尝试了很多不同的代码,但我没有找到任何解决方案。 我想做的是从 eBay 获取产品并将它们显示在我的 Chrome 扩展程序中。

感谢任何帮助。

【问题讨论】:

    标签: javascript cors ebay-api


    【解决方案1】:

    我通过发出 CORS 请求并使用来自 https://github.com/Rob--W/cors-anywhere/ 的 CORS Anywhere API 找到了解决方案

    var cors_api_url = 'https://cors-anywhere.herokuapp.com/';
    function doCORSRequest(options, printResult) {
        var x = new XMLHttpRequest();
        x.open(options.method, cors_api_url + options.url);
        x.onload = x.onerror = function() {
            printResult(
                options.method + ' ' + options.url + '\n' +
                x.status + ' ' + x.statusText + '\n\n' +
                (x.responseText || '')
            );
        };
        x.send(options.data);
    }
    (function() {
        var outputField = document.getElementById('output');
        new1();
        function new1() {
            // e.preventDefault();
            doCORSRequest({
                method: 'GET',
                url: url,
            }, function printResult(result) {
                //result contains the response
                //write your code here
            });
        };
    })();
    

    来源:https://github.com/Rob--W/cors-anywhere/blob/master/demo.html

    (现场示例:https://robwu.nl/cors-anywhere.html

    【讨论】:

      【解决方案2】:

      您可以向该 URL 发送 GET 请求。

      const http = require('http');
      
      let url = 'http://svcs.sandbox.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=NiraliAc-FlashSal-SBX-7d56b4536-d82a9262&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=harry%20potter&paginationInput.entriesPerPage=3&itemFilter(0).name=MaxPrice&itemFilter(0).value=25&itemFilter(0).paramName=Currency&itemFilter(0).paramValue=USD&itemFilter(1).name=FreeShippingOnly&itemFilter(1).value=true&itemFilter(2).name=ListingType&itemFilter(2).value(0)=AuctionWithBIN&itemFilter(2).value(1)=FixedPrice&itemFilter(2).value(2)=StoreInventory';
      
      http.get(url, res => {
          let body = '';
          res.on('data', data => body += data);
          res.on('end', () => {
              console.log(body);
          });
      });
      

      【讨论】:

      • 我正在浏览器中使用 javascript。它给了Reference error: require is not defined
      • 你可以使用jQuery $.get() 方法,或者XMLHttpRequest 就像在this 页面中一样。
      • 跨域请求会报错。我已经试过了。
      • 您好,谢谢您的帮助。我找到了解决方案。我已将其添加为答案。
      猜你喜欢
      • 2018-08-09
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2021-09-29
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多