The MERN application is functioning on the deployed Render site, however it is no longer operational when run locally

After a few months, I decided to revisit an app that was deployed on Render and noticed it was still working fine there. However, when I tried running it locally, I encountered a 500 error response in the developer tools.

network error

This is what my terminal displayed:

  VITE v5.4.0  ready in 125 ms

  ➜  Local:   http://localhost:3000/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help
10:45:13 PM [vite] http proxy error: /graphql
AggregateError
    at internalConnectMultiple (node:net:1114:18)
    at afterConnectMultiple (node:net:1667:5)

Here's my vite config:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
    proxy: {
      "/graphql": {
        target: "http://localhost:3001",
        secure: false,
        changeOrigin: true,
      },
    },
  },
  test: {
    environment: "happy-dom",
    globals: true,
  },
});

This is my server.js file:

const express = require('express');
const path = require('path');
// Import the ApolloServer class
const { ApolloServer } = require('@apollo/server');
const { expressMiddleware } = require('@apollo/server/express4');
const { authMiddleware } = require('./utils/auth');

// Import the two parts of a GraphQL schema
const { typeDefs, resolvers } = require('./schemas');
const db = require('./config/connection');

const PORT = process.env.PORT || 3001;
const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError(error) {
    console.log(error);
    return error;
  },
});

const app = express();

// Create a new instance of an Apollo server with the GraphQL schema
const startApolloServer = async () => {
  await server.start();

  app.use(express.urlencoded({ extended: false }));
  app.use(express.json());

  app.use(
    '/graphql',
    expressMiddleware(server, {
      context: authMiddleware,
    })
  );

  if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../client/dist')));

    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, '../client/dist/index.html'));
    });
  }

  db.once('open', () => {
    app.listen(PORT, () => {
      console.log(`API server running on port ${PORT}!`);
      console.log(`Use GraphQL at http://localhost:${PORT}/graphql`);
    });
  });
};
startApolloServer();

My client-side package.json:

{
  "name": "client",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  ...
}

This is my server-side package.json:

{
  "name": "apollo-mern",
  "version": "1.0.0",
  "description": "boilerplate code for MERN application",
  "main": "server/server.js",
  "scripts": {
    "start": "node server/server.js",
    "develop": "concurrently \"cd server && npm run watch\" \"cd client && npm run dev\"",
    ...
  },
  ...
}

I've spent hours researching solutions and have tried adding a proxy setting in the package.json file, adjusting server and PORT settings in both the vite config and server.js, as well as updating all dependencies.

Answer №1

Following the suggestion from Phil in his comments, I figured out that my problem was due to not having my server running when trying to access the app. To solve this, I simply ensured to run the server in one terminal and then initialize my app in a separate new terminal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to completely hide the StatusBar in React Native

Is there a way to completely hide the StatusBar, including the big white rectangle at the top, rather than just hiding the text? <StatusBar hidden/> If this code snippet only hides the text and not the entire StatusBar, how can I achieve that? Thank ...

Is Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

Utilizing a JavaScript variable within an HTML style attribute value

I have added some divs to a webpage. I am looking to adjust the width of these divs based on the browser or other settings. While I can manually set the width to 200px using inline styles, I need the flexibility to change it to 220px, 230px, or 240px depen ...

A bug in the modal dialog is causing it to disregard the value of

I want to transfer certain modal properties in this manner service.confirm = function(message, confirmProperties) { return $uibModal.open({ templateUrl: 'app/modal/alert/alert.tpl.html', controller: 'alertCon ...

Transmit information from node.js to the frontend utilizing only raw JavaScript

Seeking guidance on sending data object from a Node.js server to a JS file for frontend use. In the main.js file, DOM manipulation is performed. The following request is made: let dataName = []; let request = async ('http://localhost:3000/') =& ...

When clicking on an Ajax link inside a partial view, the partial view should be updated

I have a situation where my main view contains a partial view Main view .... .... @if (Model.ProvidedResponseCount > 0) { <div id="providedTimes" data-url="@Url.Action("ProvidedAttendeeResponse", new { attendeeId = @Model.AttendeeId })"> ...

Is it possible to retain the volume level setting?

Whenever I am playing music and adjust the volume to 20%, the settings reset to 100% when the bot leaves the voice channel. It's frustrating having to manually set it back to 20% each time. Is there a way for my bot to remember the volume setting? con ...

Filtering strings in React using the .includes() method results in an empty array

Whenever I run this sample code in a sandbox environment, it functions properly. However, when implemented in my functional component, it fails to work. I have trimmed down the code to include only the essential parts for demonstration purposes. The state ...

Encountering difficulty in assigning the desired value to the select box

// updating the subType value in the controller $scope.newEngagement.subType = 3; // creating a list of engagement subTypes $scope.engagementSubTypeList = [ { "subTypeId": 1, "subTypeName": "value1" }, { "subTypeId": 2, "subTypeName": "value2" }, { " ...

In TypeScript, both 'module' and 'define' are nowhere to be found

When I transpile my TypeScript using "-m umd" for a project that includes server, client, and shared code, I encounter an issue where the client-side code does not work in the browser. Strangely, no errors are displayed in the browser console, and breakpoi ...

Efficient method for managing complex JSON object updates using setState in React

My task involves handling structured data in JSON format, which I am unable to modify due to API restrictions. The challenge is to update the JSON file based on user modifications. { "id": 1269, "name": "Fet", &quo ...

Enhance pagination and column filtering in JQGrid without relying on local data (loadonce = false)

I'm currently facing an issue with my web application development. I am utilizing Laravel 5.8 for the backend and JQGrid version 4.6.0 to create grids. One of the grids I have is constructed with a dynamic URL that fetches JSON data from the server b ...

Typing into an autocomplete suggestion influences the activation of the submit button

Currently, I am implementing the autocomplete functionality with the google.maps.places.Autocomplete API to allow users to easily find addresses. However, when a user selects an item from the dropdown using the keyboard and hits enter, it affects the submi ...

The attribute 'map' is not recognized on the type '() => IterableIterator<number>'

I am attempting to set keys as a React prop: import * as React from "react"; import { render } from "react-dom"; const keys: string[] = ["a", "b"]; function App({keys}: string[]) { return ( <div> ...

Ways to verify whether a vue instance is empty within a .vue file by utilizing the v-if directive

I am facing an issue with a for-loop in Vue that iterates through a media object using v-for to check if it contains any images. Everything is working correctly, but I want to display a div below the loop saying "There is no media" when the object is empty ...

utilizing eval() in order to retrieve a pointer to an include

I am currently developing a form widget where the form schema is fetched from an API and generated dynamically. The library I am using for this purpose (vue-form-generator) comes with built-in validators that are directly referenced within the library itse ...

Node.js throws an error when accessing req.body as undefined

My task involved creating a basic API using node.js and express, with the addition of body-parser. However, I encountered an issue where req.body was returning undefined. Here is a snippet of my app.js: const express = require('express'); const b ...

Is there a reason to not simply reset the connection to the $.ajax?

Ensure that the server is available before loading the scripts. On the client side jQuery(document).ready(function(){ jQuery.ajax({ dataType: "jsonp", timeout: 1000, cache: false, url: "http://xxx/include/xxx.php?q=? ...

Issue: AngularJS not refreshing view after receiving server response

Currently, as I work on developing a mobile application, I've come across an issue related to relaying messages in the view after executing an ajax call and receiving data from the server. My goal is to display these messages to users only after they ...

What is the best way to open the index.html file in electron?

I'm currently developing a cross-platform app using electron and Angular. As of now, the code I have for loading my index.html file looks like this: exports.window = function window() { this.createWindow = (theBrowserWindow) => { // Create ...