我在Express.js上连接到外部API(GraphQL)时遇到问题。你能给我一些关于此的好教程吗?
还有一个问题。我有这个错误:
可以连接此API吗?
答案 0 :(得分:0)
尝试将以下中间件添加到您的NodeJS / Express应用程序中(为方便起见,我添加了一些注释):
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
希望有所帮助!