首页 \ 问答 \ 无法制作第三方API请求(Unable to make third-party API Request)

无法制作第三方API请求(Unable to make third-party API Request)

我正在开发一个Ionic 2应用程序,它使用牛津词典中的第三方API。 他们的API需要app_idapp_key作为身份验证步骤才能工作。

以下是使GET请求调用API的服务

@Injectable()
export class OxfordVocabularyService {
  private app_id: any;
  private app_key: any;
  private OxfordBaseRequestURL: any;
  constructor(private http: Http) {
    this.app_id = configuration.oxfordAPI.app_id;
    this.app_key = configuration.oxfordAPI.app_key;
    this.OxfordBaseRequestURL = configuration.oxfordAPI.requestURL;
  }


  public getWordIPA(word: String): Promise<any> {
    let headers = new Headers({ 'Accept': 'application/json' });
    headers.append('app_id', this.app_id);
    headers.append('app_key', this.app_key);
    let options = new RequestOptions({ headers: headers });
    return this.http.get(this.OxfordBaseRequestURL + word + '/pronunciations', options).toPromise().then(response => {
      console.log(response.json());
    });
  }

当应用程序运行服务调用时,它会抛出错误 在此处输入图像描述

更多浏览器请求信息: 在此处输入图像描述 在此处输入图像描述

API请求在Postman上运行得非常好 在此处输入图像描述

我已经在标头请求上附加了app_idapp_key ,为什么我会收到错误。

403 - 缺少认证参数

这是与CORS有关的吗? 你能告诉我正确调用API的方法吗?

更新

非常感谢@suraj和@ n00dl3,我通过在Ionic配置中添加代理解决了这个问题。

ionic.config.json

 "proxies": [
    {
      "path": "/oxfordapi",
      "proxyUrl": "https://od-api.oxforddictionaries.com/api/v1/entries/en"
    }
  ]

并将GET请求路径更改为

this.http.get('oxfordapi/' + word + '/pronunciations', options)

I'm working on an Ionic 2 Application, which use third-party API from Oxford Dictionary. Their API require app_id and app_key as authentication step to work.

Here is the service which make the GETrequest call to the API

@Injectable()
export class OxfordVocabularyService {
  private app_id: any;
  private app_key: any;
  private OxfordBaseRequestURL: any;
  constructor(private http: Http) {
    this.app_id = configuration.oxfordAPI.app_id;
    this.app_key = configuration.oxfordAPI.app_key;
    this.OxfordBaseRequestURL = configuration.oxfordAPI.requestURL;
  }


  public getWordIPA(word: String): Promise<any> {
    let headers = new Headers({ 'Accept': 'application/json' });
    headers.append('app_id', this.app_id);
    headers.append('app_key', this.app_key);
    let options = new RequestOptions({ headers: headers });
    return this.http.get(this.OxfordBaseRequestURL + word + '/pronunciations', options).toPromise().then(response => {
      console.log(response.json());
    });
  }

When the app run the service call, it throws err enter image description here

More request info on browser: enter image description here enter image description here

The API request works perfectly fine on Postman enter image description here

I have attached the app_id and app_key on headers request, so why do i get the error.

403 - Authentication Parameters missing

Is this something related to CORS ? Can you show me the way to make the API call properly ?

Update

Huge thanks to @suraj and @n00dl3, i have solved the problem by adding a proxy to the Ionic Configuration.

ionic.config.json

 "proxies": [
    {
      "path": "/oxfordapi",
      "proxyUrl": "https://od-api.oxforddictionaries.com/api/v1/entries/en"
    }
  ]

And change the GET request path to

this.http.get('oxfordapi/' + word + '/pronunciations', options)

原文:https://stackoverflow.com/questions/43584752
更新时间:2022-12-22 17:12

最满意答案

简短的回答是“是的”。

简化的长答案是“是的,尽管发电机有一些开销(在某种意义上是固定的,它不会随着要生成的项目数量而变化),这使得当要生成的项目数量很少时,节省的成本就会消失。” (但当然,在这种情况下,总成本足够小,无论如何都很重要)

对于长期答案过于复杂的警告:

CPython(参考Python解释器)对代码的优化很少; 它可以在非常有限的情况下进行小的窥视孔优化(例如,它可以在字节代码中将1 + 2 + x转换为3 + x ,但由于运算符重载和操作顺序,它无法x + 1 + 2转换为x + 3 ,因为它不能假设x + 1将返回一个int ,并且它无法知道对于x证明的任何类型,加法是关联的。 因此,当您在CPython中使用生成器时,它将始终在运行时作为生成器执行。

相比之下,在大多数现代浏览器中,JavaScript引擎使用JIT-ing将JavaScript代码编译为本机代码; 它可以进行推测/自适应优化 ,它可以编译为假定特定类型和值的代码,并且只有在假设失败时才会依赖于解释原始JS。 这意味着你无法确切地说出在热循环中执行生成器代码的情况下将会采取什么措施(对于长期节省而言,昂贵的分析和优化将被认为是值得的)。

如果JS引擎确定生成器通常会产生少量可以提前计算的输出(通常是完全消耗的),那么生成过程没有明显的副作用,并且它会更有效而不是如果内存密集,那么生成本机代码并不能实际创建或运行生成器,而是产生一个输出Array (或者用于数字之类的东西,可能是ES6 类型的数组以减少内存使用) 。 我不了解哪些JS引擎(如果有的话)可能尝试执行这样的优化,但考虑到过去七年左右JS引擎的最新技术发展变化(最常用的现代JS引擎是最慢的)可能至少比2008年9月1日发布V8之前最快的引擎快10倍,今天发生的优化可能很快就会明天改变。


The short answer is "Yes."

The simplified long answer is "Yes, though generators have some overhead (fixed in the sense that it doesn't change with the number of items to be generated) that make the savings vanish when the number of items to be generated is small." (but of course, in that case, the total cost is small enough that it rarely matters anyway)

Excessively complex caveat to the long answer:

CPython (the reference Python interpreter) does very little optimization of code; it can make small peephole optimizations in very limited circumstances (e.g. it can convert 1 + 2 + x to 3 + x in the byte code, but due to operator overloading and order of operations, it can't convert x + 1 + 2 to x + 3, because it can't assume x + 1 will return an int, and it can't know that addition is associative for whatever type x turns out to be). So when you use a generator in CPython, it will always be executed as a generator at run time.

By contrast, on most modern browsers, the JavaScript engine uses JIT-ing to compile the JavaScript code down to native code; it can make speculative/adaptive optimizations where it compiles to code that assumes specific types and values and falls back on interpreting the original JS only if the assumptions fail. Which means you can't actually say for sure what will be done in the case where your generator code is executed in a hot loop (where expensive analysis and optimization would be considered worthwhile for the long term savings).

If the JS engine determines that the generator is usually producing a small number of outputs that can be calculated ahead of time, that are usually fully consumed, that the generation process has no visible side-effects, and that it would be more efficient and not too memory intensive, it would be well within its rights to produce native code that doesn't actually create or run a generator, but instead produces an Array of outputs (or for stuff like numbers, perhaps an ES6 typed array to reduce memory usage). I have no insight into which JS engines, if any, might attempt to perform such an optimization, but given how rapidly state of the art has been changing for JS engines over the last seven years or so (the slowest commonly used modern JS engine is probably at least 10x faster than the fastest engine from Sept. 1, 2008, before V8 released), the optimizations that occur today could easily change tomorrow.

相关问答

更多
  • A rate of return measuring the performance of a Refunded bond, from the time of purchase to its Refund date. ( http://www.fs.ml.com/help/glossary.asp?term=y)
  • 您应该使用yield*将控件传递给另一个可迭代对象https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/yield* 您还试图在非生成器函数内部生成,但您不能。 只需使用return function* test() { yield 1; yield* [2,3].map((x) => {return x}); yield 4; } var gen = test(); console.log ...
  • 我正在寻找的其实是这样的: // correct, effects will get executed in parallel const [users, repos] = yield [ call(fetch, '/users'), call(fetch, '/repos') ] 这里call只是回复诺言 当我们产生一系列效果时,发生器会被阻止,直到所有的效果都被解决,或者一旦被拒绝(就像Promise.all的行为一样)。 What I was looking for was actuall ...
  • 您不能在异步函数中使用“return”指令。 而不是做“return(returnData)”,进行回调“回调(状态,代码,返回数据)”或简单地“回调(returnData)”。 console.log('Before http request') responseData = null; //Just declaration x.exec(params, function(status, data) { responseData = data;//You can check status to s ...
  • 我可能不完全明白你想要做什么,但也许下面的,不使用functools.partial() ,可能会有所帮助,因为它不需要索引值。 它所做的是将makePool()函数传递给一个迭代器,该迭代器将生成Parse()函数期望的配对值并将它们作为元组传递。 from multiprocessing.pool import ThreadPool def pairwise(iterable): "s -> (s0,s1), (s2,s3), (s4, s5), ..." a = iter(itera ...
  • 简短的回答是“是的”。 简化的长答案是“是的,尽管发电机有一些开销(在某种意义上是固定的,它不会随着要生成的项目数量而变化),这使得当要生成的项目数量很少时,节省的成本就会消失。” (但当然,在这种情况下,总成本足够小,无论如何都很重要) 对于长期答案过于复杂的警告: CPython(参考Python解释器)对代码的优化很少; 它可以在非常有限的情况下进行小的窥视孔优化(例如,它可以在字节代码中将1 + 2 + x转换为3 + x ,但由于运算符重载和操作顺序,它无法将x + 1 + 2转换为x + 3 , ...
  • 这是同一件事。 将块传递给布局方法,该方法将在调用时呈现文档正文。 yield实际上是Ruby中的关键字。 可以定义名为“yield”的方法(例如,Enumerator执行此操作),但是每当您看到没有接收器的yield ,它始终是将控制传递给块的相同关键字。 It's the same thing. A block is passed to the layout method that will render the document body when called. yield is actually ...
  • 必须像这样定义发电机功能 function * simpleGenerator() { # Note the `*` after `function` keyword yield "first"; yield "second"; yield "third"; }; var g = simpleGenerator(); console.log(g.next()); # { value: 'first', done: false } 引用ECMA 6的发电机功能和谐页面 , 函数 ...
  • 在您的情况下,您可以将IEnumerable直接传递给WriteFile: public static void WriteFile(IEnumerable lines) { // how to save the state, of observe an collection/stream??? using(var writer = new System.IO.StreamWriter("c:\\temp\\test.txt")) { ...
  • 我不确定这是怎么回事。 呃,是的,它应该不起作用 。 这只是因为Babel中的一个bug而起作用。 yield不返回函数引用,那么像(yield 2)那样的括号语句是什么 - 它们是没有实体的胖箭头匿名函数吗? 他们如何使用这样的部分应用程序? 不,它只是标准的功能应用,没有魔力。 yield 可以返回一个函数引用,当它发生时,这可能会起作用。 如果没有,它将在第三个.next()调用上抛出异常。 作为工作版本的示例: function* generatorFunction() { yield (yie ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)