修复响应标头返回text / html而不是application / json

时间:2015-01-09 11:40:28

标签: php content-type slim notorm

我对Slim相当新,到目前为止没有遇到任何麻烦 - 一切都按预期工作,直到这个问题。我一直在搜索和搜索,但我一定不能找到正确的地方。

我正在使用带有Slim和NotORM的AngularJS。到目前为止,我已经完成了用户身份验证工作,并且我正在处理一个简单的状态更新表单,该表单保存到数据库表中 - ' post'。表单本身很简单,只包含一个textarea元素,其中ng-model设置为' message.text'。提交时,在控制器中调用doPost(message):

$scope.doPost = function(message) {
        Data.post('message', {
            message: message
        }).then(function(results) {
            Data.toast(results);
            loadRemoteData();
        }, function(error) {
            console.log('message failed to send: ' + error);
        });
        $scope.message = {
            content: ''
        }
    }

我在数据服务中的代码(Data.post(' message'))是:

var obj = {};
obj.post = function (q, object) {
    return $http.post(serviceBase + q, object)
    .then(function(results) {
        return results.data;
    },
    function(error) {
        console.log('failed -->' + results.data + '<--');
    });
};
return obj;

然后是PHP:

$app->post('/message', function() use ($app, $db) {
    $response = array();
    $r = json_decode($app->request->getBody());
    $userid = $_SESSION['uid'];
    $displayname = $_SESSION['displayname'];
    verifyRequiredParams(array('text'), $r->message);
    $message = $db->post();
    $data = array(
        'userid' => $uid,
        'displayname' => $displayname,
         'text' => $r->message->text
    );

    $result = $message->insert($data);

    if($result != NULL) {
        $response['status'] = 'success';
        $response['message'] = 'Post successful';
        $response['id'] = $result['id'];
        echoResponse(200, $response);
    } else {
        $response["status"] = "error";
        $response["message"] = "Failed to create message. Please try again";
        echoResponse(200, $response);
    }
});

在echoResponse()中:

function echoResponse($status_code, $response) {

    $app = \Slim\Slim::getInstance();

    // Http response code
    $app->status($status_code);

    // setting response content type to json
    $app->contentType('application/json');

    echo json_encode($response);
}

这对代码来说非常重要。没有错误,但message.text不会发布到数据库,并且返回的响应为空。我在页面上创建了另一个包含text类型的输入字段的表单,它使用重复的方法工作正常。我已经尝试了我能想到的一切,而对我来说最突出的是Response-Header的Content-Type是某种方式text / html而不是application / json(测试形式显示json)。我试图发布的表格如下所示:

CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`displayname` varchar(50) CHARACTER SET utf8,
`text` text CHARACTER SET utf8,
`date` timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;

任何帮助将不胜感激。感谢。

以下是标题:

Response Headers
Access-Control-Allow-Head... origin, x-requested-with, content-type
Access-Control-Allow-Meth... PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Orig... *
Connection  Keep-Alive
Content-Length  0
Content-Type text/html
Date Fri, 09 Jan 2015 11:52:12 GMT
Keep-Alive timeout=5, max=92
Server Apache/2.2.26 (Unix) DAV/2 PHP/5.4.30 mod_ssl/2.2.26 OpenSSL/0.9.8za
X-Powered-By PHP/5.4.30

Request Headers
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length 32
Content-Type application/json;charset=utf-8
Cookie PHPSESSID=g9ooedu5kk513pk5f5djug42c4
Host localhost
Referer localhost
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:34.0) Gecko/20100101   Firefox/34.0

4 个答案:

答案 0 :(得分:2)

您可以使用以下方法设置Slim app全局内容:

$app->contentType('application/json');

答案 1 :(得分:0)

你需要获取$ response,因为它是受保护的对象......

$response = $app->response();
$response->header('Content-Type', 'application/json');

$app->render(
  file_get_contents($app->config('templates') . $template), $myPageVars
);

我选择在模板中实际计算JSON,而不是直接转储PHP数据。允许稍后更改数据源,而无需使用数据源。

答案 2 :(得分:0)

没有接受的答案,所以对于文档中的记录(Slim 3):

$newResponse = $oldResponse->withHeader('Content-type', 'application/json');

答案 3 :(得分:0)

# $result is the whatever you want to output
$response->getBody()->write(json_encode($result));
return $response->withHeader('Content-type', 'application/json');