简体   繁体   中英

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. I've searched and searched, but I must not be looking in the right place.

I'm using AngularJS with Slim and NotORM. 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'. The form itself is simple and contains only a textarea element with ng-model set to 'message.text'. When submitted, doPost(message) is called in the controller:

$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:

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:

$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():

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. 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). 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 = $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. Allows later altering your data feeds without screwing with the data source.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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