后端(Node.js + GraphQL + Express):
// server.js
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/taskapp', { useNewUrlParser: true, useUnifiedTopology: true });
const Task = mongoose.model('Task', {
title: String,
description: String,
});
const typeDefs = gql`
type Task {
_id: ID!
title: String!
description: String
}
type Query {
tasks: [Task]
task(id: ID!): Task
}
type Mutation {
createTask(title: String!, description: String): Task
}
`;
const resolvers = {
Query: {
tasks: () => Task.find(),
task: (_, { id }) => Task.findById(id),
},
Mutation: {
createTask: (_, { title, description }) => Task.create({ title, description }),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
const PORT = 4000;
app.listen({ port: PORT }, () =>
console.log(`Server running at http://localhost:${PORT}${server.graphqlPath}`)
);
确保安装相应的依赖,如@apollo/client, react-router-dom等。在实际项目中,可能需要更复杂的状态管理、错误处理和安全性实现。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。