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

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

问题描述

我开发了一个 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:

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

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