Backbone: La sincronización de CORS envía una solicitud de OPCIONES en lugar de POST

Creado en 17 may. 2013  ·  17Comentarios  ·  Fuente: jashkenas/backbone

I'm trying to use the model.save() with a rest service on another subdomain. Estoy tratando de usar model.save() con un servicio de descanso en otro subdominio. I got the following request headers which are far from my expectations: Recibí los siguientes encabezados de solicitud que están lejos de mis 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? ¿Cómo arreglar esto?

Ofc. De c. my REST server responds 404 not found for an OPTIONS call... mi servidor REST responde 404 no encontrado para una llamada de OPCIONES...

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 preguntas no deseadas: el servidor está bien, maneja bien las llamadas REST y las llamadas CORS, probado con $.ajax y una aplicación de prueba de interfaz REST también.

en

Comentario más útil

@inf3rno try this one. @ inf3rno prueba 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. Este no es un problema de Backbone en absoluto.

en

Todos 17 comentarios

Look up how CORS works -- this is the expected "preflight" request Busque cómo funciona CORS: esta es la solicitud de "verificación previa" 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

¿Cómo puedo evitar esta solicitud de reflight?

en

Solo envíe una "solicitud simple" como se define aquí: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Simple_requests

en

I tried this on server side to handle preflight calls: Intenté esto en el lado del servidor para manejar las llamadas de verificación previa:

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... pero no funcionó, el navegador no envía otra solicitud después de la verificación previa...

So you say that it is not possible with backbone.sync? ¿Entonces dices que no es posible con backbone.sync?
Then it is a bug I think... Entonces es un error, creo...

en

De todos modos, este no es un problema de Backbone, por lo que sugiero preguntar en Stackoverflow o IRC.

en

¿Puede explicarme por qué esto no es un problema de columna vertebral?

en

Lea la fuente de Backbone.sync ( http://backbonejs.org/docs/backbone.html#section-134 ) y verá que Backbone simplemente pasa todo a $.ajax.

en

@inf3rno try this one. @ inf3rno prueba 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. Este no es un problema de Backbone en absoluto.

en

These are my original headers without php: Estos son mis encabezados originales sin 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... Creo que mi servidor está bien configurado, pero probé los encabezados que diste y no funcionaron...

Simple $.ajax calls work well, for example I load json files from the service with this: Las llamadas simples $.ajax funcionan bien, por ejemplo, cargo archivos json desde el servicio con esto:

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... Probé esto con cualquier método de solicitud, y respondieron bien...

The collection.fetch() works well too, I have problems only with the model.save() ... El collection.fetch() también funciona bien, solo tengo problemas con el model.save() ...

I tried it this way, maybe I'm doing something wrong: Lo intenté de esta manera, tal vez estoy haciendo algo mal:

        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. Obtuve los atributos y el "error" en la consola. I'll check what kind of error is.. voy a ver que tipo de error es..

en

You were right, thanks! Tenías razón, gracias! I added to server config the allow content-type, and it works now. Agregué a la configuración del servidor el tipo de contenido permitido y ahora funciona. Firebug is not the best, the Chrome console printed that the content-type is not allowed... Firebug no es el mejor, la consola de Chrome imprimió que el tipo de contenido no está permitido...

en

Many tanks! ¡Muchos tanques! :D :D

en

GET and POST requests requires quite different headers. Las solicitudes GET y POST requieren encabezados bastante diferentes. When the API server uses cookies for authentication, the server should have Access-Control-Allow-Credentials: true header. Cuando el servidor API usa cookies para la autenticación, el servidor debe tener un encabezado Access-Control-Allow-Credentials: true . And off course you need to make a XHR request with withCredentials: true on client-side. Y, por supuesto, debe realizar una solicitud XHR con withCredentials: true en el lado del cliente. When the API server uses Authorization header for BasicAuth request, you don't need withCredential . Cuando el servidor API usa el encabezado Authorization para la solicitud de autenticación básica, no necesita withCredential . Instead, the Access-Control-Allow-Headers need to include Authorization in this case, just like En su lugar, los Access-Control-Allow-Headers deben incluir Authorization en este caso, al igual que

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

Ah, it seems you solved the issue while I'm writing this. Ah, parece que resolviste el problema mientras escribo esto.

en

Ye, gracias de todos modos, me ayudaste mucho!

en

@inf3rno Thanks so much for the comment about Chrome giving better error messages than Firebug! @inf3rno ¡Muchas gracias por el comentario sobre Chrome dando mejores mensajes de error que Firebug! That helped us solve the problem. Eso nos ayudó a resolver el problema.

en

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

en

En caso de que alguien más tenga este problema, tuve que agregar "x-http-method-override" a mi lista de Access-Control-Allow-Methods que se usa cuando configura Backbone.emulateHTTP = true

en
¿Fue útil esta página
0 / 5 - 0 calificaciones