[英]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.