I have created a Backbone.js model and want to save an instance to my MySql database.
var Website = Backbone.Model.extend({
defaults: {
"title":"default title"
},
urlRoot : './websites'
});
var website = new Website();
website.save();
I am using Slim.php to create a Restful API to my database. Here is the beginning of websites\index.php:
<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/websites', 'getWebsites');
$app->get('/websites/:id', 'getWebsite');
$app->post('/websites', 'addWebsite');
$app->put('/websites/:id', 'updateWebsite');
$app->delete('/websites/:id', 'deleteWebsite');
$app->run();
My save() triggers a POST which gets "moved permanently":
Request URL:localhost/SAMPLE-CODES/backbone.js-mysql-reading-json/websites Request Method:POST Status Code:301 Moved Permanently
Then I see a second http request sent:
Request URL:localhost/SAMPLE-CODES/backbone.js-mysql-reading-json/websites/ Request Method:GET Status Code:404 Not Found
My question is: why is this request not triggering the call to the 'addWebsite' function ? I see that the second http request is a GET, when it should be a POST, but even then there is a route for that...
I have a folder /websites/
I also set the the .htaccess and http.conf as per the Slim routing documentation:
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
http.conf
<VirtualHost *:80>
<Directory "c:/xampp/htdocs/SAMPLE-CODES/backbone.js-mysql-reading-json/websites/">
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Edit:
The call to model.save() triggers an http POST to
localhost/SAMPLE-CODES/backbone-mysql-reading-json/websites
.
This gets a '301 Moved Permanently' with response header says:
localhost/SAMPLE-CODES/backbone-mysql-reading-json/websites/
.
I assume this is due to the Slim recommended .htaccess settings.
Question: Is this OK to have this '301 Moved Permanently', or do I already have an issue here?
Then I see 2nd http GET to
localhost/SAMPLE-CODES/backbone-mysql-reading-json/websites/
Update:
I am still getting a 301 on
localhost/SAMPLE-CODES/backbone-mysql-reading-json/websites
, then a GET to
localhost/SAMPLE-CODES/backbone-mysql-reading-json/websites/
This second request works on a browser and returns
[{"id":"1","title":"titre site 1"},{"id":"2","title":"titre site 2"}]
So that would be the response for all records, but I wanted to save 1 record. It seems the redirect 301 is wrong.
I have a feeling it is due to Slim not finding a matching route (Slim_Exception_RequestSlash would trigger a 301).
But why my Slim script not find the route?
The request for
localhost/SAMPLE-CODES/backbone-mysql-reading-json/websites
is matched by:
$app->post('/websites', function() {