Home > front end >  Localhost 3000 cant make request to localhost 8000
Localhost 3000 cant make request to localhost 8000

Time:10-21

Hello everyone after last time I decided to refactor my code and my question. I am running a React app on localhost 3000 and a node server on port 8000. And for some reason when I try to make request to port 8000 It always hits port 3000 which can be seen on dev tools request headers like - Request URL: http://localhost:3000/. Here is what my simple node app looks like -

import dotenv from 'dotenv';
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';

// APP
const app = express();
// CORS
app.use(cors());
// LOG EVRY REQ
app.use(morgan('dev'));

app.get('/', (req, res) => {
  res.json({ key: 'success' });
});
// CONFIG
dotenv.config({ path: './config.env' });

const port = 8000;

// STARTING APP

app.listen(port, () => {
  console.log('Server listening the port 127.0.0.1:'   port   '/');
});

And in react I set proxy property to http://localhost:8000

How can I set up node and react in my localhost?

You can see all the code in my GitHub - https://github.com/SalehBal/NodeToDo

CodePudding user response:

The problem is that you are requesting / or more specifically http://localhost:3000/. This is a static resource that is served by the create-react-app infrastructure. In fact / is your main page. If / were proxied to your backend, your browser would never be able to fetch the page itself.

Instead, the proxy feature of create-react-app is designed to proxy any unknown endpoints. But / is a known request. Read the create-react-app docs about this here

Some other verboten non-proxied endpoints that are served up by your create-react-app server itself:

  • /static/js/bundle.js
  • /manifest.json
  • /favicon.ico
  • /ws
  • /logo192.png

To get your app working. Change your backend to serve up a different route - one that is different from any resource that is part of the app itself. For example: change / to /api

app.get('/api', (req, res) => {
  res.json({ key: 'success' });
});

and in your frontend, you can fetch /api. e.g.:

fetch('/api', {})

Everything should work then.

CodePudding user response:

I have modified the file (/frontend/src/utils/callApi.js) as followed.

function callApi(path, method, body, sucess, fail) {
  fetch("https://localhost:8000"   path, {    // <--- changed from "" to "https://localhost:8000"
    // headers: {
    //   Authorization: 'Basic SGVsbG8gdGhlcmUgOikgSGF2ZSBhIGdvb2QgZGF5IQ==',
    //   'Content-Type': 'application/json',
    // },
    // body: JSON.stringify(body),
  });
}
export default callApi;

Of course, you can set the domain("https://localhost:8000") as the parameter and save it in the .env file. Hope this would be helpful to you.

  • Related