Issues with response from express file to front end (React)

Asked
Active3 hr before
Viewed126 times

9 Answers

issuesexpressreactresponse
90%

Turns out the way to read and handle errors with Axios is actually error.response.data instead of just error.data in the catch() function. It’s not well highlighted but the documentation notes:,Once more, here is a large snippet from the file where a user updates their data from the client side and sends it to be saved into the database.,Express failure status code and message example

res.status(200).json('404 - no user exists in db to update');
res.status(200).send({
   message: 'user created'
});
res.status(401).send('no user exists in db to update');
load more v
88%

What you are exporting in routes.js isn't a component. Thats why you are receiving that error – Jjagwe Dennis Dec 13 '18 at 22:16 ,You have another problem in routes.js. Export a component like,I have a ReactJS project with Node/Express serving my server. On my front end (React) is serving port 3312 and on my server it's serving port (5000). When I load my front end through port 3312, everything looks great and my react router routes works fine. (My api's work everything is great). However, when I try and serve static files and see if I get the same result through my server (port 5000) I only see the styles on my page. (I have a background color) I don't see any of the html whatsoever that the static files should be serving?

Your react code is not showing up because index.html is not including it. Is public/bundle.js your transpiled react code? If so, add the following line to index.html, right after <div id="root"></div>:

<script src="/public/bundle.js"></script>

Correct me if I'm wrong, but you have not posted your index.html in its entirety. I'm guessing you already have a line that looks like <script src="/bundle.js"></script> somewhere in that .html file -- based on your latest comment, it seems it is being added by HtmlWebPackPlugin. webpack-dev-server is serving bundle.js through /, the publicPath you've specified in webpack's output option. This works just fine as long as you access your site through localhost:3312 or localhost:3000. However, your express.js server running on port 5000 has no idea webpack-dev-server is serving bundle.js at /; as a result of that, you end up seeing none of your react code when you go to localhost:5000. As for the styles, you are already serving them correctly through /public/assets/css, which the express.js server understands because you've specified that in this line: app.use("/public", express.static(__dirname + "/../public")). The solution is to change the line <script src="/bundle.js"></script> in your .html file to:

<script src="http://localhost:3312/bundle.js"></script>

Webpack Config

module.exports = {
   devServer: {
      contentBase: path.join(__dirname, "/public"),
      historyApiFallback: true,
      port: 3000,
      proxy: {
         "/api": "http://localhost:5000"
      }
   },
   entry: ["babel-polyfill", __dirname + "/src/index.js"],
   output: {
      path: path.join(__dirname, "/public"),
      filename: "bundle.js",
      publicPath: "http://localhost:3312/"
   },
   module: {
      rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: {
               loader: "babel-loader",
               query: {
                  presets: ["react", "env", "stage-0"]
               }
            }
         },
         {
            test: /\.css$/,
            use: [{
                  loader: "style-loader"
               },
               {
                  loader: "css-loader"
               },
               {
                  loader: "sass-loader"
               }
            ]
         }
      ]
   },
   plugins: [
      new BrowserSyncPlugin({
         host: "localhost",
         port: 3312,
         files: [
            "./public/*.html",
            "./public/assets/scss/*.scss",
            "./public/assets/variables/*.scss",
            "./public/assets/mixins/*.scss",
            "./public/assets/reset/*.scss"
         ],
         proxy: "http://localhost:3000/"
      })
   ]
};

index.html

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge" />
   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <meta name="theme-color" content="#000000" />
   <link href="/assets/css/styles.css" rel="stylesheet" type="text/css" />
   <title>Site</title>
</head>

<body>
   <div id="root"></div>
   <script src="http://localhost:3312/bundle.js"></script>
</body>

</html>
load more v
72%

On your code editor, let’s work in the client directory. Open app.js file located in my_awesome_project/client/app.js.,cd(change directory) into the client directory.,2. On your code editor go to the API directory and open the my_awesome_project/api/app.js file.

In your terminal, navigate to a directory where you would like to save your project. Now create a new directory for your project and navigate into it:

mkdir my_awesome_project
cd my_awesome_project
load more v
65%

Deeply-nesting callbacks, often referred to as “callback hell”, is not a Node.js issue in itself. However, this can cause problems making code quickly spin out of control:,Being careful is all it takes to avoid this Node.js error. Some Node.js developers adopt a habit of adding a return keyword before every callback invocation:,In many asynchronous functions, the return value has almost no significance, so this approach often makes it easy to avoid such a problem.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Actually, I am new in React and I am trying to fetch backend API using ‘fetch’ method which is already included in create-react-app.Here, I will tell you how to fetch data from the server side and display it on the Frontend.,Inside the express-react, run this command,Edit the ‘express-react/bin/www’ and change the port from 3000 to 3005.

Edit the ‘express-react/client/src/App.js’.

import React, { Component } from 'react';//import logo from './logo.svg';import './App.css';class App extends Component {   constructor(){       super();       this.state ={users: []};   }   componentDidMount() {          fetch('/users')            .then(res => {                console.log(res);                return res.json()             })            .then(users => {                 console.log(users);                 this.setState({ users })             });         }   render() {        return (            <div className="App">                <h1>Users</h1>                {this.state.users.map(user =>                <div key={user.id}>user: {user.name} Password: {user.password}</div>              )}            </div>        );    }}export default App;
load more v
40%

Connecting ReactJS Frontend with NodeJs Backend ,You can find the complete code for this example at FileUpload-Example Github Repository.,With these two important packages added as dependencies in our project, we can now start by modifying the default Express back-end in app.js file.

Pretag
 Pretag team - issue, fix, solve, resolve
22%

Next will need to create a server.js file. The file will contain an Express server that will act as our backend. The package.json file is auto-generated when the npm init -y command is run in the terminal.,React is a JavaScript library used to build user interfaces and develop single-page applications using reusable UI components. React is used for building frontend apps that can communicate with the backend server.,Line 3 – It will set the Express server on which port it will run on.

$cd demoreactapp
$npx create - react - app client
load more v
60%

Created and maintained by Facebook, React is a front-end library that runs on a browser. Like most libraries, this one runs on web servers like Apache or with backends like PHP or Rails.,Is React a Front-end or Backend library?,During my early correspondence with new clients, these questions typically come up without fail:  

Pretag
 Pretag team - issue, fix, solve, resolve
48%

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores. ,LogRocket is a front-end logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. You can easily monitor websockets to see if they fail as well as see users impacted by a buggy websocket connection. https://logrocket.com/signup/,Once the request is accepted in the server (after necessary validations in production), the handshake is fulfilled with status code 101. If you see anything other than status code 101 in the browser, the WebSocket upgrade has failed, and the normal HTTP semantics will be followed.

Pretag
 Pretag team - issue, fix, solve, resolve

Other "issues-express" queries related to "Issues with response from express file to front end (React)"