Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

I have an error on my code, my frontend won't be able to access my backend, but when I…

  1. User

    I have an error on my code, my frontend won't be able to access my backend, but when I only run my backend the code works perfectly.

    ntent.js:25 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}code: "ERR_NETWORK"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Network Error"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}stack: "AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:41314:14)"[[Prototype]]: Error (névtelen) @ Content.js:25 Promise.catch (aszinkron) componentDidMount @ Content.js:23 invokeLayoutEffectMountInDEV @ react-dom.development.js:25133 invokeEffectsInDev @ react-dom.development.js:27351 commitDoubleInvokeEffectsInDEV @ react-dom.development.js:27327 commitRootImpl @ react-dom.development.js:26883 commitRoot @ react-dom.development.js:26682 finishConcurrentRender @ react-dom.development.js:25981 performConcurrentWorkOnRoot @ react-dom.development.js:25809 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 Content.js:36 XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} (névtelen) @ Content.js:36 Promise.catch (aszinkron) componentDidMount @ Content.js:23 invokeLayoutEffectMountInDEV @ react-dom.development.js:25133 invokeEffectsInDev @ react-dom.development.js:27351 commitDoubleInvokeEffectsInDEV @ react-dom.development.js:27327 commitRootImpl @ react-dom.development.js:26883 commitRoot @ react-dom.development.js:26682 finishConcurrentRender @ react-dom.development.js:25981 performConcurrentWorkOnRoot @ react-dom.development.js:25809 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 Content.js:41 {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} (névtelen) @ Content.js:41 Promise.catch (aszinkron) componentDidMount @ Content.js:23 invokeLayoutEffectMountInDEV @ react-dom.development.js:25133 invokeEffectsInDev @ react-dom.development.js:27351 commitDoubleInvokeEffectsInDEV @ react-dom.development.js:27327 commitRootImpl @ react-dom.development.js:26883 commitRoot @ react-dom.development.js:26682 finishConcurrentRender @ react-dom.development.js:25981 performConcurrentWorkOnRoot @ react-dom.development.js:25809 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 xhr.js:247 GET http://localhost:5000/Feladatok/ net::ERR_CONNECTION_REFUSED dispat

    import React, { Component } from 'react'; import axios from 'axios';

    const Feladatok = props => (

    export default class FeladatokList extends Component { constructor(props) { super(props);

    this.state = {Feladatok: []};
    

    }

    componentDidMount() { axios.get('http://localhost:5000/Feladatok/') .then(response => { this.setState({ Feladatok: response.data }) }) .catch((error) => { console.log(error); }) }

    feladatList() { return this.state.Feladatok.map(currentfeladat => { return ; }) }

    render() { return ( Logged feladatok Username Description Duration Date Actions { this.feladatList() } ) } }

    const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose');

    require('dotenv').config();

    const app = express(); const port = process.env.PORT;

    app.use(cors()); app.use(express.json());

    const uri = process.env.REACT_APP_MONGODB; mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true } ); const connection = mongoose.connection; connection.once('open', () => { console.log("MongoDB database connection established successfully"); })

    const feladatokRouter = require('./routes/Feladatok');

    app.use('/Feladatok', feladatokRouter);

    app.listen(port, () => { console.log(Server is running on port: ${port}); });

    const router = require('express').Router(); let Feladatok = require('../models/Feladatok.model');

    router.route('/').get((req, res) => { Feladatok.find() .then(Feladatok => { console.log(Found ${Feladatok.length} documents); res.json(Feladatok); }) .catch(err => res.status(400).json('Error: ' + err)); });

    module.exports = router;

  2. Assistant

    It seems like you may be facing a CORS (Cross-Origin Resource Sharing) issue because your frontend is running on localhost:3000 and the backend is running on localhost:5000. In order to allow cross-origin access, you have to configure CORS in your backend.

    You already have cors included in your backend, but it's configured with the default settings. You can update the cors configuration to allow access specifically from your frontend server. Here's an updated code for your backend:

    1. Update your app.use(cors()) line in your backend to the following:
    const corsOptions = {
      origin: "http://localhost:3000",
      optionsSuccessStatus: 200
    };
    app.use(cors(corsOptions));
    

    This will allow only requests from the http://localhost:3000 origin, which is where your frontend is running.

    Now restart your backend server and test your frontend app again. The error should be resolved. If the problem persists, let me know and we can troubleshoot further.

  3. User

    I have an error on my code, my frontend won’t be able to access my backend, but when I only run my backend the code works perfectly.

    ntent.js:25 AxiosError {message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’, config: {…}, request: XMLHttpRequest, …}code: "ERR_NETWORK"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Network Error"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}stack: “AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:41314:14)”[[Prototype]]: Error (névtelen) @ Content.js:25 Promise.catch (aszinkron) componentDidMount @ Content.js:23 invokeLayoutEffectMountInDEV @ react-dom.development.js:25133 invokeEffectsInDev @ react-dom.development.js:27351 commitDoubleInvokeEffectsInDEV @ react-dom.development.js:27327 commitRootImpl @ react-dom.development.js:26883 commitRoot @ react-dom.development.js:26682 finishConcurrentRender @ react-dom.development.js:25981 performConcurrentWorkOnRoot @ react-dom.development.js:25809 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 Content.js:36 XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} (névtelen) @ Content.js:36 Promise.catch (aszinkron) componentDidMount @ Content.js:23 invokeLayoutEffectMountInDEV @ react-dom.development.js:25133 invokeEffectsInDev @ react-dom.development.js:27351 commitDoubleInvokeEffectsInDEV @ react-dom.development.js:27327 commitRootImpl @ react-dom.development.js:26883 commitRoot @ react-dom.development.js:26682 finishConcurrentRender @ react-dom.development.js:25981 performConcurrentWorkOnRoot @ react-dom.development.js:25809 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 Content.js:41 {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} (névtelen) @ Content.js:41 Promise.catch (aszinkron) componentDidMount @ Content.js:23 invokeLayoutEffectMountInDEV @ react-dom.development.js:25133 invokeEffectsInDev @ react-dom.development.js:27351 commitDoubleInvokeEffectsInDEV @ react-dom.development.js:27327 commitRootImpl @ react-dom.development.js:26883 commitRoot @ react-dom.development.js:26682 finishConcurrentRender @ react-dom.development.js:25981 performConcurrentWorkOnRoot @ react-dom.development.js:25809 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 xhr.js:247 GET http://localhost:5000/Feladatok/ net::ERR_CONNECTION_REFUSED dispat

    import React, { Component } from ‘react’; import axios from ‘axios’;

    const Feladatok = props => (

    export default class FeladatokList extends Component { constructor(props) { super(props);

    this.state = {Feladatok: []}; }

    componentDidMount() { axios.get(‘http://localhost:5000/Feladatok/’) .then(response => { this.setState({ Feladatok: response.data }) }) .catch((error) => { console.log(error); }) }

    feladatList() { return this.state.Feladatok.map(currentfeladat => { return ; }) }

    render() { return (

    const express = require(‘express’); const cors = require(‘cors’); const mongoose = require(‘mongoose’);

    require(‘dotenv’).config();

    const app = express(); const port = process.env.PORT;

    const corsOptions = { origin: "http://localhost:3000", optionsSuccessStatus: 200 }; app.use(cors(corsOptions)); app.use(express.json());

    const uri = process.env.REACT_APP_MONGODB; mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true } ); const connection = mongoose.connection; connection.once(‘open’, () => { console.log(“MongoDB database connection established successfully”); })

    const feladatokRouter = require(‘./routes/Feladatok’);

    app.use(‘/Feladatok’, feladatokRouter);

    app.listen(port, () => { console.log(Server is running on port: ${port}); });

    const router = require(‘express’).Router(); let Feladatok = require(‘…/models/Feladatok.model’);

    router.route(‘/’).get((req, res) => { Feladatok.find() .then(Feladatok => { console.log(Found ${Feladatok.length} documents); res.json(Feladatok); }) .catch(err => res.status(400).json('Error: ’ + err)); });

    module.exports = router;

  4. Assistant

    It looks like you've followed the previous suggestion to configure your CORS settings in your backend code. Here are a couple more suggestions to help troubleshoot this issue:

    1. Make sure that both your frontend and backend servers are running simultaneously.

    2. Double-check the value of the process.env.PORT variable. If it's undefined, you should provide a default port number (e.g., 5000). Update your backend code as follows:

    const port = process.env.PORT || 5000;
    

    After applying these changes, make sure to restart both your frontend and backend servers, then test the application again.

    If the issue persists, it's possible that there is a problem with the network, the browser, or an extension installed in the browser interfering with the connection. In that case, you can try the following:

    1. Test the application in a different browser or an incognito/private window.
    2. Disable browser extensions one by one and check if any of them are causing the issue.
    3. Check your computer's network settings and firewall to ensure they are not blocking the connection.

    If the problem still persists, let me know and we can further troubleshoot the issue.

  5. User
    1. Make sure that both your frontend and backend servers are running simultaneously. How can I do that?
  6. Assistant

    To ensure that both your frontend and backend servers are running simultaneously, you will need to open two separate terminal/command prompt windows (one for frontend and one for backend) and start each server independently. Follow the steps below:

    1. Open the first terminal/command prompt. Navigate to your backend project folder using the cd command. For example:
    cd path/to/your/backend/project
    
    1. Start your backend server using the appropriate command. If you're using node or nodemon, the command would look like the following:
    node server.js
    # OR
    nodemon server.js
    

    Note: Please replace server.js with the actual name of your server file if it's different.

    1. Open a new terminal/command prompt window.

    2. In this new window, navigate to your frontend project folder, which is most likely a React app:

    cd path/to/your/frontend/project
    
    1. Start your frontend server using the appropriate command. For a React app created with create-react-app, the command would look like:
    npm start
    # OR
    yarn start
    

    Now, both your frontend and backend servers should be running simultaneously on their respective ports (e.g., frontend on localhost:3000, backend on localhost:5000).