如何处理苗条框架中的POST请求?

时间:2014-06-11 12:15:40

标签: php post slim

我的 index.php 页面是

//post  : The handler POST requests
require 'Slim/Slim.php';
require 'RedBean/rb.php';

// register Slim auto-loader
\Slim\Slim::registerAutoloader();
// do initial application and database setup
R::setup('mysql:host=localhost;dbname=slim','root','root');
R::freeze(true);

// initialize app
$app = new \Slim\Slim();

// handle POST requests to /articles
$app->post('/articles', function () use ($app) {    
  try {
    // get and decode JSON request body
    $request = $app->request();
    $body = $request->getBody();
    $input = json_decode($body); 

    // store article record
    $article = R::dispense('articles');
    $article->title = (string)$input->title;
    $article->url = (string)$input->url;
    $article->date = (string)$input->date;
    $id = R::store($article);    

    // return JSON-encoded response body
    $app->response()->header('Content-Type', 'application/json');
    echo json_encode(R::exportAll($article));
  } catch (Exception $e) {
    $app->response()->status(400);
    $app->response()->header('X-Status-Reason', $e->getMessage());
  }
});

// run
$app->run();

当我加载index.php我有 404 Page Not Found 此错误时。

POST请求用于创建新项目。如何为项目创建提供数据。我的表结构是

table name: articles

id | title | url | date

我成功地为GET(对于retreive数据)请求。

所以我不知道如何在POST中使用slim请求。请为我提供有关如何使用POST请求的具体解决方案。

谢谢..

2 个答案:

答案 0 :(得分:1)

如果这是您的完整index.php,那么您没有为任何获取请求定义路由,因此在浏览器中加载页面将失败。在$app->run();之前添加以下内容,您将不会收到错误:

$app->get('/', function () {
    echo "Hello next2u";
});

我认为你真的需要阅读文档:http://docs.slimframework.com/

答案 1 :(得分:1)

这里的问题是你正在访问一些不存在的路线。

当您通过浏览器直接访问时,您发送的是GET个请求,而不是POST个请求,并且您的应用中不存在GET路由, #39;为什么你会收到这个错误。

看看cURL: http://www.php.net/manual/en/book.curl.php

或firefox RESTCLIENT或chrome POSTMAN的一些插件,用于向您的应用发送POSTPUT个请求。

相关问题