php - slim框架中如何处理POST请求?

标签 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(用于检索数据)请求。

所以我不知道如何在slim中使用POST请求。请给我一个如何使用POST请求的具体解决方案。

谢谢..

最佳答案

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

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

我认为您确实需要阅读文档:http://docs.slimframework.com/

关于php - slim框架中如何处理POST请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24162702/

相关文章:

php - 删除各种空格的单一功能

php - 禁用 jquery datepicker 日历天,基于 ajax php mysql 表

ios - 如何在 iOS 中发送对象作为 POST 请求的参数?

rest - Slim - 修改中间件内的 POST 请求正文

rest - 如何为Slim Framework中内置的REST API编写单元测试?

php - Composer 自动加载某些子文件夹中缺少的类

php - 在 PHP 中提取 ZIP 文件的子文件夹

php - 连接 3 个表并匹配空条目

java - java中通过POST方法发送Xml字符串

php - 通过javascript提交两个表单而无需点击