java调用js api,使用Java脚本调用外部API

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?

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:"

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."

解决方案

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

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).

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值