简体   繁体   English

苗条的响应标题返回text / html而不是application / json

[英]Slim response-headers returning text/html instead of application/json

I am fairly new to Slim and so far have had no trouble -- everything has worked as expected, until this issue. 我对Slim并不陌生,到目前为止没有遇到任何麻烦-一切都按预期进行,直到出现此问题为止。 I've searched and searched, but I must not be looking in the right place. 我已经搜索了,但是我一定不能在正确的地方寻找。

I'm using AngularJS with Slim and NotORM. 我在Slim和NotORM中使用AngularJS。 So far I've got user authentication working and I'm working on a simple status update form that saves to a database table - 'post'. 到目前为止,我已经进行了用户身份验证,并且正在处理一个简单的状态更新表单,该表单将保存到数据库表-“ post”中。 The form itself is simple and contains only a textarea element with ng-model set to 'message.text'. 表单本身很简单,仅包含ng-model设置为'message.text'的textarea元素。 When submitted, doPost(message) is called in the controller: 提交后,在控制器中调用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: ''
        }
    }

My code in the Data service (Data.post('message')) is: 我在数据服务(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;

And then the PHP: 然后是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);
    }
});

And in echoResponse(): 在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);
}

And that's pretty much it to the code. 这几乎就是代码。 There are no errors, but the message.text does not post to the database and the response returned is empty. 没有错误,但是message.text没有发布到数据库中,返回的响应为空。 I created another form on the page containing an input field of type text and it works fine, using duplicated methods. 我在页面上创建了另一个表单,其中包含文本类型的输入字段,并且使用重复方法可以正常工作。 I have tried everything I could think of and what stands out to me is the Response-Header's Content-Type is somehow text/html instead of application/json (the test form shows json). 我已经尝试了所有我能想到的一切,而对我而言突出的是Response-Header的Content-Type以某种方式是text / html而不是application / json(测试表单显示json)。 The table I'm trying to post to looks like this: 我尝试发布的表如下所示:

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 ;

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

Here are the headers: 这是标题:

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

您可以使用以下方法设置Slim应用程序的全局内容:

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

You need to grab the $response because it's a protected object... 您需要获取$ response,因为它是受保护的对象...

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

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

I choose to actually work out the JSON within a template rather than dumping the PHP data directly out. 我选择在模板中实际计算JSON,而不是直接转储PHP数据。 Allows later altering your data feeds without screwing with the data source. 允许以后更改数据馈送,而无需破坏数据源。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM