javascript 如何以角度发出 JSONP POST 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21352127/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:42:10  来源:igfitidea点击:

How to make a JSONP POST request in angular?

javascriptangularjs

提问by djfm

The $http.jsonp method described in the official documentation seems to always perform get requests: http://docs.angularjs.org/api/ng.$http#methods_jsonp.

官方文档中描述的 $http.jsonp 方法似乎总是执行 get 请求:http: //docs.angularjs.org/api/ng .$http#methods_jsonp。

I have tried setting the config option to 'POST' but it still sends a GET:

我尝试将配置选项设置为“POST”,但它仍然发送一个 GET:

$http.jsonp('/api/new?callback=JSON_CALLBACK', {method: 'POST'});

I have also tried setting a data argument in the hope that angular would switch to a POST:

我还尝试设置数据参数,希望 angular 能够切换到 POST:

$http.jsonp('/api/new?callback=JSON_CALLBACK', {data: {stuff: true}});

But it still doesn't :)

但它仍然没有:)

As for making a post like this:

至于发这样的帖子:

$http.post('/api/new?callback=JSON_CALLBACK')

It does make a POST obviously but doesn't do the angular magic thingy with the JSON_CALLBACK and produces the following JS error:

它确实做了一个 POST 显然,但没有用 JSON_CALLBACK 做角度魔术,并产生以下 JS 错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxx.yyy.zzz' is therefore not allowed access.

(The API is not on the same server as the app, that's the point of JSONP).

(API 与应用程序不在同一服务器上,这就是 JSONP 的重点)。

Google was most unhelpful on this issue and reading through angular's sources is not the easiest task. So how can I make a JSONP POST request with angular?

谷歌在这个问题上最没有帮助,阅读 angular 的来源并不是最简单的任务。那么如何使用 angular 发出 JSONP POST 请求呢?

回答by Quentin

You cannot make a POST request using JSON-P (with or without Angular)

您不能使用 JSON-P(有或没有 Angular)发出 POST 请求

A JSON-P request works by generating a <script>element with a srcattribute. This will always trigger a GET request.

JSON-P 请求通过生成<script>具有src属性的元素来工作。这将始终触发 GET 请求。



If you want to make a cross-domain POST request with JavaScript then you must use either XMLHttpRequest (and have the server supply suitable access control headers as per the CORS specification) or proxy the request through the server hosting the page.

如果要使用 JavaScript 发出跨域 POST 请求,则必须使用 XMLHttpRequest(并让服务器根据 CORS 规范提供合适的访问控制标头)或通过托管页面的服务器代理请求。