skip to Main Content

I am working with a React app (create using create-react-app) and using Node.js v.20.11.1 and when I try to send a POST request from my React app to my Node.js backend, the URL isn’t proxied properly. I have tried using packages such as CORS to see if it would fix it but I am just completely lost on how to fix this. I am new to React and Javascript altogether so some help would be greatly appreciated.

index.js (Node.js backend)

// Imports
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const cors = require('cors');

// Creating server instance
const app = express();

// CORS Integration
app.use(cors({
  origin:"localhost:8080",
}));

//URLS
const dbURL = "mongodb+srv://lovdaniel11:[email protected]/?retryWrites=true&w=majority&appName=Cluster0";

// Serve static files from the React build directory
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.json());  

// All other routes should redirect to the React app (for client-side routing)
app.post('/api/submitted', (req, res) => {
  // Log the submitted data
  console.log(req.body);
  // Send a response back to the client
  res.json({ message: 'Received POST request at /api/submitted' });
});
// Mongo DB Integration
mongoose.connect(dbURL)
.then(() => {
  console.info("connected to db");
})
.catch((e) => {
  console.log(`error: ${e}`);
});

// Starts server instance
const port = 8080; // Use environment variable for port
app.listen(port, () => console.log(`Server list`ening on port ${port}));

Fetch Request (React)
        let questionData = {
            question:questionVal,
            author:authorVal
        }

        fetch("/api/submitted", {
            method:'post',
            headers:{
                "Content-Type":"application/json"
            },
            body:JSON.stringify(questionData)
        })
        .then(response=>response.json())
        .then(data=>{console.log(data);});  

package.json (React)

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "options": {
    "proxy": "http://localhost:8080",
    "allowedHosts": [
      "localhost",
      ".localhost"
    ]
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "react-router-dom": "^6.23.0"
  }
}

package.json (Node.js)

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "options": {
    "proxy": "http://localhost:8080",
    "allowedHosts": [
      "localhost",
      ".localhost"
    ]
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "react-router-dom": "^6.23.0"
  }
}

Browser Error
browser error

Ideally the contents of Question and Author would be printed in my Node.js console.

2

Answers


  1. The error code 404 means the URI doesn’t exist where you’re trying to make the POST API call.
    In your screenshot, it says http://localhost:3000/api/submitted.

    • That means your Node.js application should be running on http://localhost:3000. 👉 Check if your you Node.js app running on this address/port or not?
      If not then use the same port as nodejs in the react API call.

    • Check your React app address/port. You should be using your react app port in CORS config. If your React app is running on port 5555. The config should look like this:

      app.use( cors ({ origin:"localhost:5555" }));

    Login or Signup to reply.
  2. Please all the bellow code. It will solve your issue.

    app.use((req, res, next) => {
        const allowedOrigins = ['http://localhost:8000'];
        const origin = req.headers.origin;
        
        if (allowedOrigins.includes(origin)) {
            res.setHeader('Access-Control-Allow-Origin', origin);
        }
        
        res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
        res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        res.header('Access-Control-Allow-Credentials', true);
        return next();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search