本文介绍了使用Java脚本调用外部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"标头.来源" 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

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

10-28 05:10