node.js - 如何解决 Apollo、Node 和 Next.js 中的 CORS 问题?
问题描述
我需要帮助解决我在 Apollo、Node 和 Next.js 中遇到的 CORS 错误。我不确定我做了什么改变,但突然间我无法从我的 Prisma 数据库中获取数据。我目前正在运行开发模式。我从 Prisma 中提取数据的 Yoga 服务器在 localhost:4444 运行。我的前端在 localhost:7777 上运行。
这是我的 CORS 设置:
import withApollo from "next-with-apollo";
import ApolloClient from "apollo-boost";
import { endpoint, prodEndpoint } from "../config";
import { LOCAL_STATE_QUERY } from "../components/Cart";
function createClient({ headers }) {
return new ApolloClient({
uri: process.env.NODE_ENV === "development" ? endpoint : prodEndpoint,
request: (operation) => {
operation.setContext({
fetchOptions: {
credentials: "include",
},
headers,
});
},
// local data
clientState: {
resolvers: {
Mutation: {
toggleCart(_, variables, { cache }) {
// read the cartOpen value from the cache
const { cartOpen } = cache.readQuery({
query: LOCAL_STATE_QUERY,
});
// Write the cart State to the opposite
const data = {
data: { cartOpen: !cartOpen },
};
cache.writeData(data);
return data;
},
},
},
defaults: {
cartOpen: false,
},
},
});
}
export default withApollo(createClient);
变量.env
FRONTEND_URL="localhost:7777"
PRISMA_ENDPOINT="https://us1.prisma.sh/tim-smith-131869/vouch4vet_dev_backend/dev"
PRISMA_SECRET="..."
APP_SECRET="..."
STRIPE_SECRET="..."
PORT=4444
后端 index.js
const server = createServer();
server.express.use(cookieParser());
// decode the JWT so we can get the user Id on each request
server.express.use((req, res, next) => {
const { token } = req.cookies;
if (token) {
const { userId } = jwt.verify(token, process.env.APP_SECRET);
// put the userId onto the req for future requests to access
req.userId = userId;
}
next();
});
我曾尝试回滚到以前的提交,但我没有运气。我不排除互联网问题。
如果您需要查看我的其余部分,请告诉我。
谢谢
解决方案
推荐阅读
- .net - .net 从文件中读取格式错误的 json
- sapui5 - SAPUI5 Datepicker 中的初始日期/时间
- javascript - 材质角表多行指令
- elasticsearch - TFS 2017 工作项搜索索引问题
- python - 将列表列表的第一个字符串元素转换为元组
- android - 如何在 Android 中使用新的 Dialogflow SDK V2
- textures - 提高 Direct3D 中纹理样本的质量
- unity3d - 在不使用 Vuforia 的情况下使用 Unity 进行文本识别
- react-native - 使用数组排序反应原生性能问题
- ruby-on-rails - 无法发现堆栈级别太深的错误