Backbone & Slim PHP - Access-Control-Allow-Headers - Can GET information, can't POST it?

后端 未结 4 1593
北海茫月
北海茫月 2020-12-29 16:46

I\'m using Backbone and the Slim PHP framework. I\'m trying to post information to my API, however Access-Control-Allow-Headers keeps causing me problems...

My conso

4条回答
  •  萌比男神i
    2020-12-29 17:21

    In your javascript client you're making an OPTIONS request to /user/auth, but in your PHP code you're only accepting POST requests through this endpoint.

    If you want your API to accept OPTIONS method you should have something like this in your code:

    $app->options('/user/auth', function () use ($app) {
        //code here
    });
    

    Or, if you want to handle multiple HTTP methods in the same function:

    $app->map('/user/auth', function () use ($app) {
        if ($app->request()->isOptions()) {
            //handle options method
        }
    
        else if ($app->request()->isPost()) {
            //handle post method
        }
    })->via('POST', 'OPTIONS');
    

    Keep in mind that the OPTIONS method, according to W3C:

    [...] represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

    Alternatively, just change your client's code to make a POST request instead of OPTIONS request. It's easier and makes more sense than authenticating a user through the OPTIONS method. In zepto.js it would be something like this:

    $.post('/user/auth', { foo: 'bar' }, function(response){ 
        console.log(response);
    });
    

提交回复
热议问题