我正在尝试遵循有关 django and graphql
的文档
https://www.techiediaries.com/django-graphql-tutorial/graphene/
我距离使用 graphql
进行测试仅完成了一半查看并提出我们的查询。
然后我停下来尝试做一些前端工作来使用ajax进行查询
正在阅读
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>
最佳答案
看来您需要更改 ajax 调用以包含完整的 URL。
改变
url: 'localhost:8000/graphql/'
至
url: 'http://localhost:8000/graphql/'
关于javascript - 如何使用 get 方法将 ajax 与 graphql 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46721015/