我正在尝试使用Django、Graphene和NextJs构建一个简单的待办事项应用程序。我可以在graphiQL和postman中创建待办事项,但是当我尝试在NextJs中创建待办事项时,我从服务器收到了400错误请求。我尝试使用纯ReactJs做同样的事情,但我仍然收到了同样的错误。下面是错误x1c 0d1x
这是我的models.py文件
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=255)
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
这是我的待办事项/schema.py文件
import graphene
from graphql import GraphQLError
from .models import Todo
from graphene_django import DjangoObjectType
class TodoType(DjangoObjectType):
class Meta:
model = Todo
class Query(graphene.ObjectType):
todos = graphene.List(TodoType)
def resolve_todos(self, info):
return Todo.objects.all()
class CreateTodo(graphene.Mutation):
todo = graphene.Field(TodoType)
class Arguments:
title = graphene.String()
def mutate(self, info, title):
user = info.context.user
if user.is_anonymous:
raise GraphQLError('Login to add a todo!')
todo = Todo(title=title)
todo.save()
return CreateTodo(todo=todo)
class Mutation(graphene.ObjectType):
create_todo = CreateTodo.Field()
这是我的apollo-client.js文件
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
const httpLink = createHttpLink({
uri: "http://localhost:8000/graphql",
});
const client = new ApolloClient({
link: httpLink,
credentials: "include",
cache: new InMemoryCache(),
});
export default client;
这是我的addtodo.js文件
import { useMutation } from "@apollo/client";
import { CreateTodoMutation } from "graphql/mutations";
import { useState } from "react";
import { Button, Container, Form } from "react-bootstrap";
const AddTodo = () => {
const [title, setTitle] = useState("");
const [createTodo] = useMutation(CreateTodoMutation);
const handleSubmit = (e) => {
e.preventDefault();
createTodo({ variables: { title } });
};
return (
<Container>
<h3>Add Todo</h3>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Label>Project Title</Form.Label>
<Form.Control
type="text"
placeholder="Project Title"
onChange={(e) => setTitle(e.target.value)}
/>
</Form.Group>
<Button variant="primary" type="submit">
Add
</Button>
</Form>
</Container>
);
};
export default AddTodo;
请我希望有人能帮我找出我在这里做得不正确的地方。
1条答案
按热度按时间3htmauhk1#
您是否尝试移除CSRF安全性功能?您可以将它新增到要求的信头中,或移除它以取得较不安全的解决方案。请尝试并查看是否可以运作。
第一个月
下面是Twilio写的一篇很好的文章。下面的部分解释了如何从请求中免除CSRF令牌:https://www.twilio.com/blog/graphql-apis-django-graphene