[英]How to fetch a query/mutation to graphene-django API from JavaScript?
当用户提交表单时,我试图进行突变,但我总是得到 400 错误。
奇怪的是,我使用 GraphiQL 接口来检查他们如何获取 function,最后,他们使用完全相同的标头、方法、正文和凭据。 所以我真的不知道该怎么做。
这是突变:
const comp_1 = (<HTMLInputElement>document.getElementById('comp-1')).value.trim();
const comp_2 = (<HTMLInputElement>document.getElementById('comp-2')).value.trim();
const mutation = `
mutation CreateComps($comp1: String!, comp2: String!) {
createCompetitors(comp1: $comp1, comp2: $comp2) {
comp1 {
id
name
}
comp2 {
id
name
}
}
}
`;
fetch('/graphql/#', {
method: 'POST',
headers: {
"Content-Type": 'application/json',
"Accept": 'application/json',
"X-CSRFToken": getCookie('csrftoken')
},
body: JSON.stringify({
mutation,
variables: { comp_1, comp_2 }
}),
credentials: 'include',
})
.then(response => {
if (!response.ok) {
throw Error(`${response.statusText} - ${response.url}`);
}
return response.json();
})
.then(result => {
console.log(result)
})
.catch(err => {
if (err.stack === 'TypeError: Failed to fetch') {
err = 'Hubo un error en el proceso, intenta más tarde.'
}
useModal('Error', err);
})
这是 GraphiQL function:
function httpClient(graphQLParams, opts) {
if (typeof opts === 'undefined') {
opts = {};
}
var headers = opts.headers || {};
headers['Accept'] = headers['Accept'] || 'application/json';
headers['Content-Type'] = headers['Content-Type'] || 'application/json';
if (csrftoken) {
headers['X-CSRFToken'] = csrftoken
}
return fetch(fetchURL, {
method: "post",
headers: headers,
body: JSON.stringify(graphQLParams),
credentials: "include",
})
.then(function (response) {
return response.text();
})
.then(function (responseBody) {
try {
return JSON.parse(responseBody);
} catch (error) {
return responseBody;
}
});
}
我收到一个 400 错误,它只是说: Failed to load resource: the server responded with a status of 400 (Bad Request)
,并且 Django output 说:
Bad Request: /graphql/
[07/Feb/2021 12:51:44] "POST /graphql/ HTTP/1.1" 400 294
但事实并非如此。 在此之后,我尝试使用名为grapql-request
(链接) 的 npm package ,但我不知道代码是否正确,因为无论我做什么,我都会在导入时出错。
你必须导入两件事,我这样做: import { GraphQLClient, gql } from "graphql-request"
(就像文档所说的那样),然后在浏览器控制台中我收到一个错误: Uncaught TypeError: Failed to resolve module specifier "graphql-request". Relative references must start with either "/", "./", or "../"..
Uncaught TypeError: Failed to resolve module specifier "graphql-request". Relative references must start with either "/", "./", or "../"..
node_modules 目录位于项目目录的下方,因此它处于最高级别。 我尝试像这样导入: import { GraphQLClient, gql } from "../../../../node_modules/graphql-request"
,并得到这个错误: GET http://127.0.0.1:8000/node_modules/graphql-request net::ERR_ABORTED 404 (Not Found).
我想如果我把它移到应用程序的 static 目录,它可以工作,所以我试了一下,像这样导入: import { GraphQLClient, gql } from "../../node_modules/graphql-request"
和importing in the html file like this: <script src="{% static 'node_modules/graphql-request' %}" type="module"></script>
, and now I still get the same error from before: GET http://127.0.0.1:8000/static/node_modules/graphql-request net::ERR_ABORTED 404 (Not Found)
所以我真的不知道该怎么办。 如果有人可以帮助我,我会非常高兴,因为自星期四以来我在获取 GraphQL API 时遇到问题,我真的很接近重做应用程序,但使用django-rest-framework
顺便说一句,这是我正在使用的 URL:
path('graphql/', GraphQLView.as_view(graphiql=False))
您在查询中有一个 sintax 错误: $comp1: String,: comp2: String!
. 您必须在comp2
之前添加$
。
在body
中,这样做:
body: JSON.stringify({
query: mutation,
variables: { comp1: comp_1, comp2: comp_2 }
})
之前的身体是这样的:
{
mutation: <the mutation>,
variables: {
comp_1: <comp_1>,
comp_2: <comp_2>
}
}
这样做的问题是没有查询, graphql 需要一个,并且查询中没有名为comp_1
的变量,有一个名为comp1
,对于comp_2
。
并添加: credentials: 'include'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.