YII2 DOC-2.0:RESTFUL POST示例返回无效的json

时间:2016-03-01 07:01:23

标签: rest yii2

当我在http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html中使用命令时:

curl -i -H "Accept:application/json" -H "Content-Type:application/json" -XPOST   "my api path/users" -d '{"username": "testuser", "email": "user@123.com"}'

它返回:

HTTP/1.1 400 Bad Request
Date: Tue, 01 Mar 2016 06:51:03 GMT
Server: Apache/2.4.4 (Win32) PHP/5.6.9
X-Powered-By: PHP/5.6.9
Vary: Accept-Encoding
Content-Length: 148
Connection: close
Content-Type: application/json; charset=UTF-8

{"name":"Bad Request","message":"Invalid JSON data in request body: Syntax error
.","code":0,"status":400,"type":"yii\\web\\BadRequestHttpException"}curl: (6) Co
uld not resolve host: testuser,
curl: (6) Could not resolve host: email
curl: (3) [globbing] unmatched close brace/bracket at pos 13

1 个答案:

答案 0 :(得分:0)

检查您的行为方法:

public function behaviors()
{
    return [
        [
           'class' => 'yii\filters\ContentNegotiator',
           'only' => ['index', 'view','create'],
           'formats' => ['application/json' => Response::FORMAT_JSON,],

        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'index'=>['get'],
                'view'=>['get'],
                'create'=>['post'],
                'update'=>['post'],
                'delete' => ['delete'],
                'deleteall'=>['post'],
            ],

        ],
    ];
}

我尝试使用POSTMAN。如果您要发送原始数据,请在数据之前和之后删除单引号。喜欢{" usename":" sdasda" ...}