Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a RESTful service for Backbone.js with apache and windows

I'm trying to set up a RESTful web service on my apache localhost to serve as the back-end for my backbone app. I have tried:

  1. Setting up WebDAV, but get the following error messages in the logs

    [Thu Feb 23 21:46:17 2012] [error] [client 127.0.0.1] Unable to PUT new contents for /clusters/19. [403, #0], referer: http://ideas.localhost/ [Thu Feb 23 21:46:17 2012] [error] [client 127.0.0.1] An error occurred while opening a resource. [500, #0], referer: http://ideas.localhost/

  2. Using Backbone.emulateHTTP, which causes a 405 method not allowed error (something I guess is caused by the X-HTTP-Method-Override: PUT header as normal POST requests are working fine

I'm running Apache 2.2.21 and PHP 5.3 on windows 7, and below is my .htaccess file. I'm also using the SLIM framework to handle url routing.

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

And virtual host config

<VirtualHost *:80>
    DocumentRoot "G:/sites/ideas"
    Dav On // I also had security setting set to Allow all as it's just my localhost
    ServerName ideas.localhost
    ErrorLog "logs/ideas.localhost-error.log"
    CustomLog "logs/ideas.localhost-access.log" combined
    SetEnv APPLICATION_ENV development
</VirtualHost>

I've been struggling to get something to work for ages, so any help greatly appreciated.

like image 787
wheresrhys Avatar asked Oct 09 '22 14:10

wheresrhys


1 Answers

Can't believe I solved the problem less than an hour after opening a bounty, but hey ho.

The problem was that Slim doesn't have a built in ability to handle the X-HTTP-Method-Override header used by backbone and the error message isn't very descriptive. Adding the following at the bottom of request.php and using emulateHTTP mode in Backbone fixed it

protected function checkForHttpMethodOverride() {
    if ( isset($this->post[self::METHOD_OVERRIDE]) ) {
        $this->method = $this->post[self::METHOD_OVERRIDE];
        unset($this->post[self::METHOD_OVERRIDE]);
        if ( $this->isPut() ) {
            $this->put = $this->post;
        }
    } else if(isset($this->headers['x-method-override'] )) {
        $this->method = $this->headers['x-method-override'];
        if ( $this->isPut() ) {
            $this->put = $this->post;
        }
    }
}

PS - I've created a pull request for SLIM to include this by default, so if you think it'd be a good idea to include this in the framework please leave a comment there

like image 162
wheresrhys Avatar answered Oct 12 '22 11:10

wheresrhys