bac*_*113 7 cookies apollo reactjs graphql prisma
我正在使用 graphql-yoga 中的 GraphQLServer 来处理请求。此时我的后端能够与我的 React 前端进行通信,我可以进行 graphql 查询并获得响应。
我最近被告知我应该使用令牌设置 cookie,而不是在突变响应中返回它。所以我试图切换,但 cookie 没有被突变设置。
服务器.js(节点)
import { GraphQLServer, PubSub } from 'graphql-yoga';
import {resolvers, fragmentReplacements} from './resolvers/index'
import prisma from './prisma'
const pubsub = new PubSub()
export default new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers,
context(request) {
return {
pubsub,
prisma,
request, //fragmentReplacements[], request, response
}
},
fragmentReplacements
});
Run Code Online (Sandbox Code Playgroud)
Mutation.js(节点)
export default {
async createUser(parent, args, {prisma, request}, info) {
const lastActive = new Date().toISOString()
const user = await prisma.mutation.createUser({ data: {...args.data, lastActive }})
const token = generateToken(user.id)
const options = {
maxAge: 1000 * 60 * 60 * 24, //expires in a day
// httpOnly: true, // cookie is only accessible by the server
// secure: process.env.NODE_ENV === 'prod', // only transferred over https
// sameSite: true, // only sent for requests to the same FQDN as the domain in the cookie
}
const cookie = request.response.cookie('token', token, options)
console.log(cookie)
return {user}
},
// more mutations...
Run Code Online (Sandbox Code Playgroud)
console.log(cookie) 输出附加了 cookie
索引.js(反应)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import ApolloClient, { InMemoryCache, create } from 'apollo-boost';
import {ApolloProvider} from 'react-apollo'
const client = new ApolloClient({
uri: 'http://localhost:4000',
cache: new InMemoryCache(),
credentials: 'include',
request: async operation => {
operation.setContext({
fetchOptions: {
credentials: 'same-origin'
}
})
},
})
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
谢谢你的时间!
您需要将凭据包含在 ApolloClient 中
fetchOptions: {
credentials: 'include'
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15188 次 |
| 最近记录: |