gpt4 book ai didi

node.js - 在本地主机开发模式下从 Next.js 应用程序请求在不同端口上运行的 Graphql api

转载 作者:搜寻专家 更新时间:2023-10-31 23:45:28 25 4
gpt4 key购买 nike

我目前正在将我现有的应用程序从 create-react-app 切换到 next.js,一切似乎都正常工作,除了我的 api 端点在端口 4000 上的另一个 Node 应用程序上运行,我无法从我的 next.js 应用程序访问它。我按照 repo 协议(protocol)中的示例进行操作,但我无法使其工作,在生产中我使用 nginx 作为反向代理没有问题,但我处于开发模式。为了使用 Redux 设置 Apollo,我遵循了这个例子:with-apollo-and-redux对于代理,我使用了这个例子 with-custom-reverse-proxy

我知道,我做错了什么,我只是暂时想不通

在 initApollo.js 中

...    
function create() {
return new ApolloClient({
ssrMode: !process.browser,
networkInterface: createNetworkInterface({
uri: "/api"
})
});
}
...

在 server.js 中

...    
const devProxy = {
"/api/": {
target: "http://localhost:4000/api/",
changeOrigin: true
}
};

app
.prepare()
.then(() => {
const server = express();

if (dev && devProxy) {
const proxyMiddleware = require('http-proxy-middleware')
Object.keys(devProxy).forEach(function (context) {
server.use(proxyMiddleware(context, devProxy[context]))
})
}

server.all("*", (req, res) => handle(req, res));

server.listen(3000, err => {
if (err) throw err;
console.log("> Ready on http://localhost:3000");
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});

最佳答案

好的,我终于找到了与 Next.js 或 Apollo 客户端相关的问题。而是我的服务器运行在端口 4000(我的 graphql 服务器)上。我不得不处理 CORS 和 express 中间件 express-graphql,我认为默认情况下不支持它。

所以我将以下内容添加到运行 graphql 的服务器

app.use("/api", function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With"
);
if (req.method === "OPTIONS") {
res.sendStatus(200);
} else {
next();
}
});

而且在 apollo 客户端中,我必须将绝对路径放入我的 api 服务器

networkInterface: createNetworkInterface({
uri: "http://localhost:4000/api/"
})

就是这样

关于node.js - 在本地主机开发模式下从 Next.js 应用程序请求在不同端口上运行的 Graphql api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com