【问题标题】:Front-end app Graphql request blocked by Safari, Firefox, but not Chrome on Heroku前端应用 Graphql 请求被 Safari、Firefox 阻止,但 Heroku 上的 Chrome 没有阻止
【发布时间】:2019-07-14 22:01:09
【问题描述】:

当我在 Heroku 上部署我的应用程序时,它在 Chrome 上运行良好,但无法在 Firefox 和 Safari 上加载。 Heroku Log 没有显示特别的错误: Heroku Log

在 Firefox 的控制台中,它显示:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4000/graphql. (原因:CORS 请求未成功)。

这是我的服务器设置

require('dotenv').config();
const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require('./schema/schema');
const mongoose = require('mongoose');
const cors = require('cors');

mongoose.connect(process.env.mongodburi, { useNewUrlParser: true })

mongoose.connection.once('open', ()=>{
  console.log('Connected to database');
});

const app = express();
app.use(cors());
app.use(express.static("public"));

app.use('/graphql', graphqlHTTP({
  schema,
  graphiql: true
}));

app.withCredentials = true;

const port = process.env.PORT;
app.listen(port, ()=>{
  console.log(`Now listening requests on port:${port}`);
})

有些人似乎说这是一个安全许可证问题。知道如何解决吗?

【问题讨论】:

  • 如果您删除此行是否有效:app.use(cors()); ?
  • 试过了。没用...
  • 我认为您的服务器设置很好,但是您如何在客户端连接?看来您正在使用http://localhost:4000/graphql 尝试使用heroku url。
  • 我不知道为什么它仍然调用本地主机。在 Chrome 上,网络向 localhost:4000/graphql 发出相同的请求,但它可以工作。这是最让我困惑的地方。

标签: javascript express heroku graphql graphql-js


【解决方案1】:

我整天都在面对同样的问题,我刚刚弄清楚出了什么问题。

首先,我从前端的uri 中删除了localhost,如下所示:

// It was "http://localhost:4000/graphql" before 
const httpLink = new HttpLink({ uri: '/graphql' });

const apolloClient = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});

仍然在前端,我创建了一个代理脚本,因此它不会在开发时破坏应用程序:(package.json)

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": { //... },
   // ...,

   // This line below
   "proxy": "http://localhost:4000"
}

最后在后端,我的server.js 文件几乎和你的一样,除了这一行:

app.get('*', (request, response) => {
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'));
}); 

// This chunk of code is here just as a reference
const port = process.env.PORT;
app.listen(port, ()=>{
  console.log(`Now listening requests on port:${port}`);
})

因此,在进行这些更改之后,我再次在客户端运行 npm run build,同时致力于 github 和 heroku,它的魅力在于。

我希望它可以帮助别人。

【讨论】:

    猜你喜欢
    • 2015-08-10
    • 2018-06-28
    • 1970-01-01
    • 2016-01-29
    • 2014-03-18
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多