Backbone: A sincronização CORS envia uma solicitação OPTIONS em vez de POST

Criado em 17 mai. 2013  ·  17Comentários  ·  Fonte: jashkenas/backbone

I'm trying to use the model.save() with a rest service on another subdomain. Estou tentando usar o model.save() com um serviço de descanso em outro subdomínio. I got the following request headers which are far from my expectations: Recebi os seguintes cabeçalhos de solicitação que estão longe das minhas expectativas:

OPTIONS /user HTTP/1.1
Host: not.public
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://not.public
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

How to fix this? Como consertar isto?

Ofc. Claro. my REST server responds 404 not found for an OPTIONS call... meu servidor REST responde 404 não encontrado para uma chamada OPTIONS ...

To avoid unwanted questions: the server is ok, it handles REST calls and CORS calls well, tested with $.ajax and a REST interface tester application too. Para evitar perguntas indesejadas: o servidor está ok, ele lida bem com chamadas REST e chamadas CORS, testado com $.ajax e um aplicativo de teste de interface REST também.

en

Comentários muito úteis

@inf3rno try this one. @inf3rno tente este.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: POST');

This isn't Backbone issue at all. Isso não é problema de Backbone.

en

Todos 17 comentários

Look up how CORS works -- this is the expected "preflight" request Veja como o CORS funciona - esta é a solicitação de "comprovação" esperada

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Preflighted_requests https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Preflighted_requests

en

Como posso evitar este pedido de revoo?

en

Apenas envie uma "solicitação simples" conforme definido aqui: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Simple_requests

en

I tried this on server side to handle preflight calls: Eu tentei isso no lado do servidor para lidar com chamadas de comprovação:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');

but did not work, the browser does not send another request after the preflight... mas não funcionou, o navegador não envia outra requisição após o preflight...

So you say that it is not possible with backbone.sync? Então você diz que não é possível com backbone.sync?
Then it is a bug I think... Então é um bug eu acho...

en

Independentemente disso, este não é um problema de backbone, então sugiro perguntar no Stackoverflow ou no IRC.

en

Você pode me explicar por que isso não é um problema de backbone?

en

Leia a fonte do Backbone.sync ( http://backbonejs.org/docs/backbone.html#section-134 ) e você verá que o Backbone simplesmente passa tudo para $.ajax.

en

@inf3rno try this one. @inf3rno tente este.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: POST');

This isn't Backbone issue at all. Isso não é problema de Backbone.

en

These are my original headers without php: Estes são meus cabeçalhos originais sem php:

HTTP/1.1 200 OK
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Server: Microsoft-IIS/7.5
X-Powered-By: PHP/5.3.8, ASP.NET
access-control-allow-origin: http://x.y.loc
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Date: Fri, 17 May 2013 01:33:02 GMT
Content-Length: 0

I think my server is well configured, but I tried out the headers you gave, and they did not work... Acho que meu servidor está bem configurado, mas testei os cabeçalhos que você deu e não funcionaram...

Simple $.ajax calls work well, for example I load json files from the service with this: Chamadas $.ajax simples funcionam bem, por exemplo, eu carrego arquivos json do serviço com isto:

define(function (require, exports, module) {
    var $ = require("jquery");

    module.exports = {
        load: function (name, _require, load, config) {
            var params = name.split("|");
            var method, url;
            if (params.length == 1) {
                method = "GET";
                url = params[0];
            }
            else {
                method = params[0];
                url = params[1];
            }
            $.ajax({
                url: url,
                type: method,
                dataType: "json"
            }).success(load).error(function (xhr, status, error) {
                    throw error;
                });
        }
    };

});

I tried out this with any request method, and they responded well... Eu tentei isso com qualquer método de solicitação e eles responderam bem ...

The collection.fetch() works well too, I have problems only with the model.save() ... O collection.fetch() funciona bem também, tenho problemas apenas com o model.save()...

I tried it this way, maybe I'm doing something wrong: Eu tentei assim, talvez eu esteja fazendo algo errado:

        var User = Backbone.Model.extend({
            urlRoot: Application.service.Authorization.User.create.url
        });
        var form = new UserForm({
            model: new User({
                email: "[email protected]",
                name: "test"
            })
        }).render();
        form.on("submit", function (user) {
            console.log(user.attributes);
            user.save(null, {
                success: function (model, response, options) {
                    console.log("success");
                },
                error: function (model, xhr, options) {
                    console.log("error");
                }
            });
        });

I got the attributes and "error" in console. Eu tenho os atributos e "erro" no console. I'll check what kind of error is.. Vou verificar que tipo de erro é..

en

You were right, thanks! Você estava certo, obrigado! I added to server config the allow content-type, and it works now. Eu adicionei à configuração do servidor o tipo de conteúdo permitir e funciona agora. Firebug is not the best, the Chrome console printed that the content-type is not allowed... Firebug não é dos melhores, o console do Chrome imprimiu que o tipo de conteúdo não é permitido...

en

Many tanks! Muitos tanques! :D :D

en

GET and POST requests requires quite different headers. As solicitações GET e POST requerem cabeçalhos bem diferentes. When the API server uses cookies for authentication, the server should have Access-Control-Allow-Credentials: true header. Quando o servidor de API usa cookies para autenticação, o servidor deve ter o cabeçalho Access-Control-Allow-Credentials: true . And off course you need to make a XHR request with withCredentials: true on client-side. E, claro, você precisa fazer uma solicitação XHR com withCredentials: true no lado do cliente. When the API server uses Authorization header for BasicAuth request, you don't need withCredential . Quando o servidor de API usa o cabeçalho Authorization para a solicitação BasicAuth, você não precisa withCredential . Instead, the Access-Control-Allow-Headers need to include Authorization in this case, just like Em vez disso, o Access-Control-Allow-Headers precisa incluir Authorization neste caso, assim como

header('Access-Control-Allow-Headers: Authorization, Content-Type');

Ah, it seems you solved the issue while I'm writing this. Ah, parece que você resolveu o problema enquanto eu escrevia isso.

en

Sim, obrigado de qualquer forma, você ajudou muito!

en

@inf3rno Thanks so much for the comment about Chrome giving better error messages than Firebug! @inf3rno Muito obrigado pelo comentário sobre o Chrome dando melhores mensagens de erro do que o Firebug! That helped us solve the problem. Isso nos ajudou a resolver o problema.

en

You're welcome! De nada! :-) :-)

en

Caso alguém esteja tendo esse problema, tive que adicionar "x-http-method-override" à minha lista de Access-Control-Allow-Methods que é usado quando você define Backbone.emulateHTTP = true

en
Esta página foi útil?
0 / 5 - 0 avaliações