【问题标题】:node.js sending ajax request using "request/request" package sends no data to servernode.js 使用“request/request”包发送 ajax 请求不向服务器发送数据
【发布时间】:2015-08-31 07:37:09
【问题描述】:

我正在尝试使用 https://github.com/request/request 库从 node.js 脚本向 php 脚本发送一些数据,但似乎 lib 没有发送任何数据。

我的 test.js:

var request = require('request');

var value = {
    trueProperty: true,
    falseProperty: false,
    numberProperty: -98346.34698,
    stringProperty: 'string',
    nullProperty: null,
    arrayProperty: ['array'],
    objectProperty: { object: 'property' }
};

var options = {
    method: 'POST',
    uri: 'http://127.0.0.1/test.php',
    json: true,
    body: value,
};

request(options, function (error, response, json) {
    if (!error && response.statusCode == 200) {                                                     
        console.log(json);                  
    } else {
        console.log('Error has occurred:');

        if(error){
            console.log(error)
        }

        if(response){
            console.log("Response status code: " + response.statusCode);
        }
    }
});

我的 test.php 脚本:

<?php

echo json_encode(
    array(
        'REQUEST' => $_REQUEST,
        'GET' => $_GET,
        'POST' => $_POST
    )
);

当我运行 test.js 脚本时,结果是:

> node test.js
{ REQUEST: [], GET: [], POST: [] }

知道什么是错的吗?

更新 我修改了 test.php 以返回请求正文:

echo json_encode(
    array(
        'REQUEST' => $_REQUEST,
        'GET' => $_GET,
        'POST' => $_POST,
        'BODY' => print_r(file_get_contents('php://input'), true)
    )
);

现在节点的输出如下:

{ REQUEST: [],
  GET: [],
  POST: [],
  BODY: '{"trueProperty":true,"falseProperty":false,"numberProperty":-98346.34698,"stringProperty":"string","nullProperty":null,"arrayProperty":["array"],"objectProperty":{"object":"property"}}' }

所以只是 PHP 没有处理数据,是它们发送不正确还是什么?

【问题讨论】:

  • 我的猜测是你没有在 php 端正确访问数据,但我对 php 的了解不够确定。
  • @KevinB,你说得对,我已经更新了我的帖子。仍然不知道如何发送数据,所以 PHP 会正确处理它。
  • php 正在处理数据,你只是没有处理它。它是json,现在你需要解析它。
  • 从正文更改为表单,使数据像往常一样发送,您可以从 $_POST 变量(或 $_REQUEST)中读取它,并且由于 json: true 仍然会自动解析响应。
  • 你应该发布一个答案并接受它,因为你知道它是如何工作的。

标签: ajax json node.js request send


【解决方案1】:

通过将 body 键更改为 form 键设置的修改选项使 php 将变量放置在 $_POST 和 $_REQUEST 数组中,json: true 保持不变事实上,它会自动响应我们的请求 JSON.parse-d。

更新后的选项如下:

var options = {
    method: 'POST',
    uri: 'http://127.0.0.1/test.php',
    json: true,
    form: {
        data: JSON.stringify(value),
    }
};

现在我们可以读取 $_POST['data'] 并在其上使用 json_decode。

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 2018-01-31
    • 2012-01-03
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多