为什么请求的主体是空的?

时间:2016-03-17 09:49:42

标签: node.js express

我使用其他项目中的模式将JSON数据发送到节点。在另一个项目中,它不起作用。 req-object是valide,但是body是空的。为什么呢?

客户端:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://tlstest.paypal.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 6); // CURL_SSLVERSION_TLSv1_2
curl_setopt($ch, CURLOPT_CAINFO,  'cacert.pem');
$result = curl_exec($ch);
echo 'result = '.$result.'<br>';
echo 'errno = '.curl_errno($ch).'<br>';
echo 'error = '.curl_error($ch).'<br>';
curl_close($ch);

服务器端:

json = { "auth_user_pkref": 2 }
        json.test_id = "ANCA"
        json.questions_count = 3
        json.right_answers = 2
        json.wrong_answers = 1
        json.seconds_spent = 180

        console.log('/api/answer/add', json);
        $.ajax({
            url: "/api/answer/add",
            type: "post",
            data: JSON.stringify(json),
            contentType: "application/json",
            success: function (data) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("ERROR, DB error");
            }
        });

服务器日志:

router.post('/api/answer/add', function (req, res) {
    console.log('/api/answer/add: ', req.body)

1 个答案:

答案 0 :(得分:1)

    json = { "auth_user_pkref": 2 }
    json.test_id = "ANCA"
    json.questions_count = 3
    json.right_answers = 2
    json.wrong_answers = 1
    json.seconds_spent = 180

    console.log('/api/answer/add', json);
    $.ajax({
        url: "/api/answer/add",
        type: "post",
        data: json,
        contentType: "application/json",
        success: function (data) {

        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("ERROR, DB error");
        }
    });

试试这个