使用 Javascript 调用外部 API [英] Calling External API with Javascript

查看:32
本文介绍了使用 Javascript 调用外部 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Javascript 从我的网页向外部服务器发出 POST 请求.正文和响应都是 json.我不知道如何拨打这个电话或使用什么工具.我如何拨打这个电话?

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?

这是我目前使用 jQuery 和 ajax 所拥有的:

This is what I have so far using jQuery and ajax:

var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
           url: "http://" + environment + "/vizportal/api/web/v1/getViews",
           method: "post",
           dataType:'json',
           data: JSON.stringify(body),
           headers: {
            'Content-Type': 'text/plain',
            'X-XSRF-TOKEN' : XSRFToken,
            'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
           },
           success:function(response){
                alert("success");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
                alert("Status: " + textStatus); alert("Error: " + errorThrown); 
            } 
        });

它正在抛出一个只说状态:"和错误:"的警报

It is throwing a alerts that just says "Status:" and "Error:"

控制台说这个XMLHttpRequest 无法加载 http://[domain]/vizportal/api/web/v1/getViews.请求的资源上不存在Access-Control-Allow-Origin"标头.Origin 'http://[domain]' 因此不允许访问.响应的 HTTP 状态代码为 405."

The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."

推荐答案

您是通话目的地的所有者吗?如果是,请在服务器端实现 CORS 标头.

Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.

如果不是,您可以使用 JSONP(它绕过 CORS)或者您甚至可以实现您拥有的服务器端代理来路由外部请求(当然,在那里实现 CORS).

If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).

如果您想了解更多信息,请查看 MDN 中关于 CORS 的文章:HTTP 访问控制 (CORS) 在 MDN

Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN

这篇关于使用 Javascript 调用外部 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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