如何跳过“选项"预检请求? [英] How to skip the OPTIONS preflight request?

查看:581
本文介绍了如何跳过“选项"预检请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了PhoneGap应用程序,现在正在将其转换为移动网站.除了一处小故障,一切都可以顺利进行.我通过POST请求使用了某个第三方API,该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的权限(因此无法在那一侧进行更改),但是他们已将我正在处理的域添加到其Access-Control-Allow-Origin标头中.

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.

这是我正在谈论的代码:

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);
        });

如何防止浏览器(或AngularJS)发送该OPTIONS请求,而仅跳至实际的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.

提前谢谢.

推荐答案

预检是由您的application/json的Content-Type触发的.防止这种情况的最简单方法是在您的情况下将Content-Type设置为text/plain. application/x-www-form-urlencoded& 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.

如果进行此更改后仍然看到预检,则Angular可能也在请求中添加了X-header.

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

或者您可能具有将触发它的标头(授权,缓存控制...),请参见:

Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:

这篇关于如何跳过“选项"预检请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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