使用 Fetch 模块读取从 Nodejs 发送的 php 中的 JSON 对象
Reading a JSON object in php sent from Nodejs with Fetch module
我正在尝试 Post 从 Nodejs 到 LAMP 服务器的 JSON 对象。
我可以发送对象,但无法从我的 php 脚本中获取它。
我需要有关在 php 脚本中获取对象的帮助。
始终return -- 未设置 --
为什么 ?
我该怎么做 ?
谢谢
我的代码是:
**In express**
module.exports = function(app){
var fetch = require('node-fetch');
var request = require('request-promise');
//Save
app.post('/cajaSave', function(req, res)
{
var pago = req.body; //object to send
fetch('http://www.myurl/myscript.php',{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(pago)
})
.then(function(res) {
return res.json();
})
.then(function(json) {
console.log(json);
})
.catch(function(err) {
console.log(err);
});
});
My php code is:
<?php
header('Access-Control-Allow-Origin: *');
$json = $_POST['body'];
if(isset($_POST['body']))
{
$msg = "set";
}
else
{
$msg = "not set";
}
echo json_encode($msg);
?>
JSON 被转储到 php://input
$_POST = json_decode(file_get_contents('php://input'), true);
我正在尝试 Post 从 Nodejs 到 LAMP 服务器的 JSON 对象。 我可以发送对象,但无法从我的 php 脚本中获取它。 我需要有关在 php 脚本中获取对象的帮助。
始终return -- 未设置 -- 为什么 ? 我该怎么做 ? 谢谢
我的代码是:
**In express**
module.exports = function(app){
var fetch = require('node-fetch');
var request = require('request-promise');
//Save
app.post('/cajaSave', function(req, res)
{
var pago = req.body; //object to send
fetch('http://www.myurl/myscript.php',{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(pago)
})
.then(function(res) {
return res.json();
})
.then(function(json) {
console.log(json);
})
.catch(function(err) {
console.log(err);
});
});
My php code is:
<?php
header('Access-Control-Allow-Origin: *');
$json = $_POST['body'];
if(isset($_POST['body']))
{
$msg = "set";
}
else
{
$msg = "not set";
}
echo json_encode($msg);
?>
JSON 被转储到 php://input
$_POST = json_decode(file_get_contents('php://input'), true);