如何跳过AngularJS的OPTIONS preflight要求 [英] How to skip the OPTIONS preflight request in AngularJS

查看:644
本文介绍了如何跳过AngularJS的OPTIONS preflight要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了目前正在转化为移动网站的PhoneGap应用程序。一切工程进展顺利,除了一个小小的故障。我通过一个POST请求,这在应用程序工作正常,但未能在移动网站版本使用某些第三方API。

I had developed a PhoneGap app which is now being transformed to a mobile website. Everything works smoothly besides one small glitch. I use a certain third party API via a POST request, which works fine in the app, but fails in the mobile website version.

在仔细一看,好像AngularJS(我猜其实浏览器)先发送一个OPTIONS请求。今天我学到了很多关于CORS,但我似乎无法弄清楚如何禁用它。我没有访问该API(因此在那面的变化是不可能的),但他们增加了我的工作给他们的域名访问控制允许来源头。

After a closer look it seems like AngularJS (I guess the browser actually) is first sending an OPTIONS request. I learned a lot today about CORS, but I can't seem to figure out how to disable it altogether. I do not have access to that API (so changes at that side are impossible), but they have added the domain I am working on to their Access-Control-Allow-Origin header.

这是code我说的是:

This is the code I am talking about:

        var request = {
                language: 'fr',
                barcodes: [
                    {
                        barcode: 'somebarcode',
                        description: 'Description goes here'
                    }
                ]
            };
        }
        var config = {
            headers: { 
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/json'
            }
        };
        $http.post('http://somedomain.be/trackinginfo', request, config).success(function(data, status) {
            callback(undefined, data);
        }).error(function(data, status) {
            var err = new Error('Error message');
            err.status = status;
            callback(err);
        });

我如何prevent浏览器(或AngularJS)发送的选项要求,只是跳到实际POST请求?我使用AngularJS 1.2.0。

How can I prevent the browser (or AngularJS) from sending that OPTIONS request and just skip to the actual POST request? I am using AngularJS 1.2.0.

先谢谢了。

推荐答案

在preflight正在由应用/ JSON你的内容类型触发。以prevent最简单的方法,这是设置内容类型,以你的情况text / plain的。应用程序/ x-WWW的形式urlen codeD&放大器;的multipart / form-data的内容类型也可以接受,但当然,你需要适当地格式化您的请求负载。

The preflight is being triggered by your Content-Type of "application/json". The simplest way to prevent this is to set the Content-Type to be "text/plain" in your case. application/x-www-form-urlencoded & multipart/form-data Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.

如果你仍然在进行此更改后看到preflight,那么角可能会增加一个X头请求为好。

If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.

这篇关于如何跳过AngularJS的OPTIONS preflight要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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