从浏览器客户端JavaScript调用Easypost API [英] Calling Easypost API from browser client javascript

查看:163
本文介绍了从浏览器客户端JavaScript调用Easypost API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从javascript/jquery调用Easypost API(是的,我知道这是一个坏"主意,因为JS代码包含明文帐户密钥,但是此JS和HTML在我们网站的安全部分中仅适用于特别授权的人员.

I am trying to call Easypost APIs from javascript/jquery (yes, I know it is a "bad" idea because the JS code contains the cleartext account key, but this JS and HTML are in a secure section of our web site available only to specifically authorized people).

我的电话就像:

$.ajax({
    url: uri,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    headers: {
        "Authorization": "Basic " + btoa(username + ":" + password)
    },
    success: function(result) {...},
    error: function(...) {...}
 });

返回404,Chrome显示此错误:

It returns 404 and Chrome shows this error:

无法加载 https://api.easypost.com/v2/shipments:对预检请求的响应未通过访问控制检查:在所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源' https://localhost .响应的HTTP状态代码为404.

Failed to load https://api.easypost.com/v2/shipments: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access. The response had HTTP status code 404.

这可能吗?

推荐答案

这意味着easypost API服务器不接受CORS请求或源自localhost的请求.

That means the easypost API server does not accept CORS request or requests originating from localhost.

根据他们的文档,他们仅提供服务器端库以与其API进行交互.我的猜测是您将无法从Web应用程序直接与其交互.

Based on their documentation, they only provide server side libraries to interact with their API. My guess is you won't be able to interact directly with it from your web app.

您最好的选择是使用代理,您可以自己开发代理,也可以使用 node -http-proxy 代理您的API调用. (有php或python等效项)

Your best bet is to use a proxy, you can develop one yourself or use something like node-http-proxy to proxy your API calls. (There are php or python equivalents)

代理服务器将能够发出请求,然后将其转发到您的应用.

The proxy server will be able to issue the requests and will then forward them to your app.

建议您进一步阅读:在Google上输入了解CORS 并了解更多信息.

Suggested further reading: type understanding CORS on google and read more about it.

这篇关于从浏览器客户端JavaScript调用Easypost API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆