Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

414
Visualizações
Failed To Fetch From Server Using Node.js and Heroku

I am trying to deploy my React app onto Heroku however I'm running into some graphql errors. When I manually deploy the app, the server and client both start up successfully however upon performing any actions that require a database fetch, I get a failed to fetch error and a "Failed to load resource: net::ERR_CONNECTION_REFUSED" error. I think this is because the server is in the correct location (IP-wise) but this app was created to run locally so the client is expected to be on the localhost network, not the heroku url it has now. I have changed the ENV variables various different times to see what combination of addresses would work for the server and client however nothing changed. I will post my server side code and ENV variables below:

const { ApolloServer } = require('apollo-server-express');
const cors = require('cors');
const express = require('express');
const mongoose = require('mongoose');
const resolvers = require('./resolvers/root-resolver');
const { typeDefs }  = require('./typedefs/root-def');
const serverOptions = require('./server-config');
require('dotenv').config();
const { MONGO_URI, BACKEND_PORT, CLIENT_LOCAL_ORIGIN, SERVER_LOCAL_DOMAIN } = process.env;

// create express server handling our middleware 
const app = express();

// since we presume cors is enabled, this next step is not optional, so cors
// is enable here instead of in options
app.use(cors({ origin: CLIENT_LOCAL_ORIGIN, credentials: true }));

const corsPolicy = async(req, res, next) => {
    /*
        TODO for 316 students: res.set(), Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers,
        have them set these, inspect error messages, understand why they're needed
    */
    res.set("Access-Control-Allow-Origin", req.headers.origin.toString());
    res.set("Access-Control-Allow-Credentials", true);
    next();
}

app.options('*', cors());
app.use(corsPolicy);


// middleware application is configured to happen in server-config.js
serverOptions(app);

const server = new ApolloServer({
    typeDefs: typeDefs,
    resolvers: resolvers,
    context: ({req, res}) => ({ req, res })
});

// since the express server has cors configured, cors on the apollo server
// can be false; passing the same options as defined on the express instance
// works as well
server.applyMiddleware({ app , cors: false});

mongoose.connect(MONGO_URI, {useNewUrlParser: true , useUnifiedTopology: true})
        .then(() => {
            app.listen({ port: BACKEND_PORT }, CLIENT_LOCAL_ORIGIN, () => {
                console.log(`Server ready at ${SERVER_LOCAL_DOMAIN}:${BACKEND_PORT}`);
            })
        })
        .catch(error => {
            console.log(error)
        });

[ENV Variables][1] [1]: https://i.stack.imgur.com/5nqmp.png

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda