如何使用getql方法与graphql一起使用ajax?

问题描述:

我想按照这个文件约django and graphql如何使用getql方法与graphql一起使用ajax?

https://www.techiediaries.com/django-graphql-tutorial/graphene/

我只有一半的地方,我们可以做的graphql视图测试,使我们的查询。

然后我停下来,试图做一些前端工作,使阿贾克斯

查询在读

https://blog.graph.cool/how-to-use-graphql-with-jquery-51786f0a59cb

即使在博客,它使用post。我相信使用get不应该有太大的不同。

所以我试图使query成一个字符串,然后JSON.stringify他们在把它传递到后端django但我不断收到错误

这是错误我

XMLHttpRequest cannot load localhost:8000/graphql/?{"query":"query { allProducts {id sku title description } }"}. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

这是html + jquery

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
    <button class="graphql-test">CLICK</button> 
</body> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 
    <script> 
     $(function(){ 
      $('.graphql-test').on('click', function(e){ 
       e.preventDefault(); 


       var query = "query { allProducts {id sku title description } }"; 

       $.ajax({ 
        method: 'get', 
        url: 'localhost:8000/graphql/', 
        data: JSON.stringify({"query": query}), 
        contentType: 'application/json', 
        success: function(data){ 
         console.log(data); 
        }, 
        error: function(data){ 
         console.log(data); 
        } 

       }) 
      }) 
     }); 
    </script> 
</html> 
+0

没有我的回答下面为您解决? –

+0

@MikeGorski没有运气:( – Dora

看起来你需要改变你的ajax调用来包含完整的URL。

变化

url: 'localhost:8000/graphql/' 

url: 'http://localhost:8000/graphql/' 
+0

我只是试图...没有运气:( – Dora

+0

让我去虽然:D另一个愚蠢的错误,我有这就是为什么它不工作 – Dora