将Apollo反应到不同端口上的graphql-php服务器

问题描述 投票:1回答:1

我正在尝试使用Apollo将我的create-react-app前端连接到我的graphql-php服务器。由于两者都在我本地机器上的不同端口上运行(分别为3000和8080),我遇到了一些CORS问题。 Apollo正在发送一个OPTIONS请求,然后抛出一个控制台日志消息:

 DOMException: Failed to execute 'postMessage' on 'Window': Error: Network request failed with status 200 - "OK" could not be cloned.
        at ApolloClient.hookLogger [as devToolsHookCb] (<anonymous>:14:14)
        at QueryManager.onBroadcast (http://localhost:3000/static/js/bundle.js:2585:27)
        at QueryManager../node_modules/apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (http://localhost:3000/static/js/bundle.js:3659:14)
        at http://localhost:3000/static/js/bundle.js:3230:31
        at <anonymous>

会喜欢任何人可以提供的任何帮助,如何让这两个人互相交谈!

前端Apollo配置:

const httpLink = new HttpLink({uri:'http://localhost:8080/temps_api/index.php'}); //TODO: Separate into config file
const client = new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache()
});

的index.php

<?php
require_once 'vendor\autoload.php';
require_once 'core\bootstrap.php';

header('Access-Control-Allow-Origin: *');

use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use Temps\Types\Types;

$schema = new Schema([
    'query' => Types::query()
]);

// $data = Data::parseInput();

var_dump(file_get_contents('php://input'));

//Test query
// $data = [
//   'query' => '
//     {
//         user(email: "[email protected]", password: "password") {
//             __typename,
//             username,
//             userType,
//             email
//         }
//     }'
// ];
//This method will vlidate the POST variables and turn them into $data array

$result = GraphQL::executeQuery(
    $schema,
    $data['query']
);

echo json_encode($result);
reactjs cors react-apollo graphql-php
1个回答
0
投票

您必须在回显结果之前设置几个标题。像这样

header('Content-Type: application/json', true, $httpStatus);
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
    }
}

header('Access-Control-Allow-Origin: *');
echo json_encode($result);
exit;
© www.soinside.com 2019 - 2024. All rights reserved.