【问题标题】:YII2 DOC-2.0: RESTFUL POST example return invalid jsonYII2 DOC-2.0:RESTFUL POST 示例返回无效的 json
【发布时间】:2016-06-13 11:56:52
【问题描述】:

当我在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

【问题讨论】:

  • 尝试删除 JSON 中的空格。
  • 您也可以将 JSON 放入文件并在 cURL 中使用 --data @data.json 发送
  • "my api path/users"您使用的是url路径,而不是包含应用程序的文件夹的路径,对吧?

标签: rest yii2


【解决方案1】:

检查你的行为方式:

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"...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 2013-12-20
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多