2

我正在尝试从 POST 请求中获取 JSON 信息。我的 POST 请求是:

var money = document.getElementById("code").value;
const Http = new XMLHttpRequest();
const url='/paypal/';
Http.open("POST", url);
Http.setRequestHeader("Content-Type", "application/json");
Http.send(JSON.stringify({
    value: money
}));

控制器是:

public function paypal(Request $r) {
$postInput = file_get_contents('php://input');
$data = json_decode($postInput, true);
$response = array('value' => $data);
return Response::json($response);
}

但我得到的唯一结果是:

{"value":null}

知道我的问题在哪里吗?

4

3 回答 3

0

使用 POST 请求时不要忘记在 headers 中设置 csrf 令牌

添加元标记<meta name="csrf-token" content="{{ csrf_token() }}">

let token = document.head.querySelector('meta[name="csrf-token"]')          
var money = document.getElementById("code").value;
const Http = new XMLHttpRequest();
const url = '/paypal';
Http.open("POST", url);
Http.setRequestHeader("Content-Type", "application/json");
Http.setRequestHeader('X-CSRF-TOKEN', token.content);
Http.send(JSON.stringify({value: money}));

要从控制器检索 JSON 有效负载,请使用:

$data = json_decode($request->getContent(), true);
return response()->json($data);

并确保可变货币具有正确的价值

于 2020-04-10T00:03:00.500 回答
0

谢谢你们的帮助。我通过 GET 请求发布所有内容来解决我的问题。

于 2020-04-10T15:00:23.677 回答
-1

对于 laravel,我们可以更简单的方式获取 POST JSON。

use Illuminate\Http\Request;


public function test(Request $request) {
    $inputData = $request->json()->all();
}
于 2020-04-10T00:56:57.967 回答