我是GraphQL新手,我想要构建一个简单的API来开始。在阅读了文档并试用了示例之后,API终于可以正常工作了.但是!
这个API的php实现以一个" echo“结尾(这对于Graphiql客户端来说很好!),但是当我试图在cURL中获得响应时,这个回显出现在我的页面源中.
拜托,伙计们,如何避免这种回声,并在cURL中得到结果?我求助于巨大的集体智慧,以便在这方面得到一些帮助。
以下是我使用的资源:
这是实现webonyx/graphql-php
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
require('types.php');
require('querys.php');
require('mutations.php');
$schema = new Schema([
'description' => 'Available querys and mutations',
'query' => $rootQuery,
'mutation' => $rootMutation
]);
try
{
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$result = GraphQL::executeQuery($schema, $query);
$output = $result->toArray();
}
catch (\Exception $e){
$output = [
'error' => [
'message' => $e->getMessage()
]
];
}
header('Content-Type: application/json');
echo json_encode($output); //<-- This echo appear when i try to get the response in cURL
这里是GraphiQL中的查询
mutation{
addUser(name:"user name",email:"user email",password:"some pass"){
id
}
}
这里是GraphQL的结果(一切都很好!):
{
"data": {
"addUser": {
"id": 97
}
}
}
下面是cURL中的函数以获得响应:
function addUser($name,$email,$password){
$query = <<<'JSON'
mutation{
addUser(name:"*name", email:"*email", password:"*password"){
id
name
}}
JSON;
$trans = array(
"*name" => $name,
"*email" => $email,
"*password" => $password
);
$query = strtr($query, $trans);
$variables = "";
$json = json_encode(['query' => $query, 'variables' => $variables]);
$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, $this->endpoint);
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, false);
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($chObj, CURLOPT_VERBOSE, true);
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($chObj);
return $result;
}
这是我页面中使用该函数时的源代码:
{"data":{"addUser":{"id":98,"name":"user name"}}}[1]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.87.0">
<title>Dashboard Template · Bootstrap v5.1</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/dashboard/">
字符串:{“addUser”:{“addUser”:{“id”:98,"name":"user“}来自API实现echo json_encode($output);
我尝试使用get_file_content而不是cURL,但不能取得好的效果,请任何帮助将不胜感激!
发布于 2021-08-17 22:12:08
将
CURLOPT_RETURNTRANSFER
设置为true,将传输作为curl_exec()返回值的字符串返回,而不是直接输出它。
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);
https://stackoverflow.com/questions/68824489
复制相似问题