skip to Main Content

I have created a react app using create-react-app and an express server using express-generator. My react app is running on http://localhost:3000 and my express server is running on http://localhost:8080. In my component I am making a POST fetch request to my express server, which is successfully running my express router code, returning a 200 response status code. However, the client console logs the following error and does not receive the response:

Proxy error: Could not proxy request /components/findAlbumArt from localhost:3000 to http://localhost:8080.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

In the browser under the network tab I can see that the findAlbumArt request now has the status (canceled).

My react code:

import React, { Component } from "react";

class Search extends Component {
  constructor(props) {
    super(props);
    this.state = { value: "" };
  }

  handleChange = (event) => {
    this.setState({ value: event.target.value });
  };

  handleSubmit = async (event) => {
    let response = await fetch("/components/findAlbumArt", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        value: this.state.value,
      }),
    });

    response = await response.json();

    this.props.setAlbumArt(response.albumArtUrl);
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Find an album that you love:{" "}
          <input
            type="text"
            value={this.state.value}
            onChange={this.handleChange}
          />
        </label>{" "}
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Search;

My express code:

const express = require("express");
const cache = require("../bin/cache/cache");
const axios = require("axios");
const router = express.Router();

router.post("/findAlbumArt", async (req, res, next) => {
  res
    .status(200)
    .json({
      albumArtUrl:
        "https://i.scdn.co/image/ab67616d0000b2739feadc48ab0661e9b3a9170b",
    });

    // I commented out my other code to simply test returning a success response
  });

module.exports = router;

Other relevant files:

app.js

const express = require("express");
const path = require("path");
const createError = require("http-errors");
const logger = require("morgan");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");

let app = express();

const indexRouter = require("./routes/index");
const componentsRouter = require("./routes/components");

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");

app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/components", componentsRouter);
app.use("/", indexRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;

express package.json

{
  "name": "onboarding",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "dev": "nodemon ./bin/www",
    "start": "node ./bin/www"
  },
  "dependencies": {
    "async-redis": "^1.1.7",
    "axios": "^0.19.2",
    "body-parser": "^1.19.0",
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "2.0.0-beta11"
  }
}

client package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8080",
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Any help would be greatly appreciated. Thank you!

2

Answers


  1. Chosen as BEST ANSWER

    Solved the problem myself actually. I was missing event.preventDefault(); in the handleSubmit() handler function.

    The browser page was reloading when the submit button was clicked, causing the request to be canceled before completing.


  2. Perhaps the window is being refreshed. Maybe forgot to prevent default behavior.

    I was getting the same error when I was (purposely) refreshing a page for testing purposes. I removed the

    window.location.reload(); command

    and the proxy error disappeared.

    just re-render the react component instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search