
GraphQL 作为一种现代 API 查询语言,凭借其高效、灵活和强大的数据获取能力,广泛应用于现代 Web 应用程序。
首先,搭建 GraphQL 服务器。安装 GraphQL Yoga 并创建一个简单的 GraphQL schema:
<code class="bash">npm init -y npm install graphql yoga graphql-yoga</code>
<code class="javascript">// server.js
const { GraphQLServer } = require('graphql-yoga');
const typeDefs = `
type Query {
hello: String
}
type Mutation {
addMessage(message: String!): String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
Mutation: {
addMessage: (_, { message }) => `You added the message "${message}"`,
},
};
const server = new GraphQLServer({ typeDefs, resolvers });
server.start(() => console.log(`服务器运行在 http://localhost:4000`));</code>接下来,在前端应用中配置 Apollo Client 与 GraphQL 服务器通信:
<code class="bash">npm install apollo-boost @apollo/client graphql</code>
<code class="javascript">// client.js
import ApolloClient from 'apollo-boost';
import { InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
cache: new InMemoryCache(),
});
export default client;</code>在 React 组件中使用 Apollo Client 执行查询和变更:
<code class="javascript">// App.js
import React from 'react';
import { gql, useQuery, useMutation } from '@apollo/client';
import client from './client';
const GET_HELLO = gql`
query GetHello {
hello
}
`;
const ADD_MESSAGE_MUTATION = gql`
mutation AddMessage($message: String!) {
addMessage(message: $message)
}
`;
function App() {
const { loading, error, data } = useQuery(GET_HELLO);
const [addMessage, { data: mutationData }] = useMutation(ADD_MESSAGE_MUTATION);
if (loading) return <p>加载中...</p>;
if (error) return <p>错误 :(</p>;
return (
<div>
<h1>{data.hello}</h1>
<button onClick={() => addMessage({ variables: { message: 'Hello from frontend!' } })}>
添加消息
</button>
{mutationData && <p>新消息: {mutationData.addMessage}</p>}
</div>
);
}
export default App;</code>我们使用 GET_HELLO 查询获取服务器的问候语,并使用 ADD_MESSAGE_MUTATION 变更在用户点击按钮时向服务器发送新消息。
启动后端服务器:
ShopNum1是武汉群翔软件有限公司自主研发的基于 WEB 应用的 B/S 架构的B2C网上商店系统,主要面向中高端客户,为企业和大中型网商打造优秀的电子商务平台, ShopNum1运行于微软公司的 .NET 平台,采用最新的 ASP.NET 3.5技术进行分层开发。 拥有更强的安全性、稳定性、易用性 。ShopNum1分销系统是实现您货源网络分销,代理渠道网络拓展、品牌直销店连锁加盟的一套B2
0
<code class="bash">node server.js</code>
然后启动前端应用 (假设使用 Create React App):
<code class="bash">npm start</code>
GraphQL 查询和变更使用类似 JSON 的结构表示:
<code class="graphql"># 查询示例
query GetUser {
user(id: 1) {
name
email
}
}
# 变更示例
mutation CreateUser {
createUser(name: "Alice", email: "alice@example.com") {
id
name
}
}
# 订阅示例 (假设使用 WebSocket)
subscription OnNewUser {
newUser {
id
name
}
}</code>后端定义 GraphQL schema 描述这些类型:
<code class="graphql">type User {
id: ID!
name: String!
email: String!
}
type Mutation {
createUser(name: String!, email: String!): User
}
type Subscription {
newUser: User
}</code>查询结构由字段和参数组成。
GraphQL 查询可以嵌套。
以上就是GraphQL 在现代 Web 应用程序中的应用和优势的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号