【发布时间】: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