使用 Javascript 调用外部 API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33309824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling External API with Javascript
提问by anton2g
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?
我需要使用 Javascript 从我的网页向外部服务器发出 POST 请求。正文和响应都是 json。我不知道如何拨打这个电话或使用什么工具。我如何拨打这个电话?
This is what I have so far using jQuery and ajax:
这是我到目前为止使用 jQuery 和 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."
控制台显示“XMLHttpRequest 无法加载http://[domain]/vizportal/api/web/v1/getViews。请求的资源上不存在“Access-Control-Allow-Origin”标头。Origin' http:// [域]' 因此不允许访问。响应的 HTTP 状态代码为 405。”
采纳答案by Mathieu Amiot
Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.
您是呼叫目的地的所有者吗?如果是,请在服务器端实现 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).
如果没有,您可以使用 JSONP(它绕过 CORS)或者您甚至可以实现您拥有的服务器端代理来路由外部请求(当然,在那里实现 CORS)。
Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN
如果您想了解更多信息,请查看 MDN 中关于 CORS 的文章:MDN 上的HTTP 访问控制 (CORS)
回答by Arthur Medeiros
You can use JQUERY and AjAX. You can send/get information information to/from your API either by post or get method.
您可以使用 JQUERY 和 AjAX。您可以通过 post 或 get 方法向/从您的 API 发送/获取信息信息。
It would be something like that:
它会是这样的:
$("#ButtonForm").click(function(){
$.ajax({
url:(Your url),
dataType:'json',
type: 'post',
data: yourForm.serialize(),
success:function(response){
** If yout API returns something, you're going to proccess the data here.
}
});
});
回答by Fluster
You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.
您在这里违反了所谓的同源政策。大多数浏览器不允许脚本访问与脚本所在页面具有不同主机名和端口的 URL。这是一项非常严格的安全策略,即使是出于测试目的,通常也很难克服。
Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.
传统上,解决此问题的最简单方法是使用您自己的网站作为代理,并通过它将请求转发到外部服务器。但是,如果您对自己的站点没有足够的控制权来实施这样的解决方案,事情就会变得更加复杂。如果你用“同源策略”在互联网上搜索,你会发现很多关于这个话题的讨论和其他解决它的想法。
My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.
我的第一个建议是检查您的错误消息提到的“Access-Control-Allow-Origin”,尽管我自己并不熟悉。它与一个名为 CORS 的新方案有关,该方案最近(2014 年)已添加到 W3C 建议中,并且似乎在许多浏览器的最新版本中得到广泛支持。也许我们开发人员终于得到了一些工具来处理这个恼人的问题。
回答by Mitul
When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.
当您想使用不同域的 ajax 调用时,您需要使用 JSONP 数据类型,这将允许浏览器进行跨域请求。
Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/
这是 JSONP 的更多文档:https: //learn.jquery.com/ajax/working-with-jsonp/
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:'jsonp',
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);
}
});
回答by Darlan Mendon?a
If you use jquery, use .post, or .ajax, to submit
如果使用 jquery,请使用 .post 或 .ajax 提交
$.post(url, data, callbackSuccess, callbackError);
$.post(url, data, callbackSuccess, callbackError);
more about these methods here http://api.jquery.com/jquery.ajax/
更多关于这些方法的信息在这里http://api.jquery.com/jquery.ajax/
example:
例子:
var url = 'http://example.com/path/endpoint';
$.post(url, {name: 'Darlan', lastname: 'Mendon?a'}, function(response){
// callback success
}, function(response) {
// callback error
});