Pass the JSX data as JSON from the Express backend and showcase it as a component in the React frontend

I am currently developing a basic react front-end paired with an Express backend. Is it possible for me to have express send JSX data as JSON so that I can fetch it in react and utilize it as a component? Right now, I am sending JSON data and successfully displaying it in react as a component. How can I achieve sending JSX data as JSON?

Here is the current code snippet, React front-end:-

import React, { Component } from "react";
import "./App.css";

class App extends Component {
  state = { users: [] };

  componentDidMount() {
    fetch("http://localhost:3001/users")
      .then(res => res.json())
      .then(users => this.setState({ users }))
      .catch(error => { });
  }

  render() {
    return <div className="App">
        <h1>Users</h1>
        {this.state.users.map(user => <div key={user.id}>
            {user.username}
          </div>)}
      </div>;
  }
}

export default App;

Express Backend:-

var express = require("express");
var router = express.Router();

/* GET users listing. */
router.get("/", function(req, res, next) {
  // Comment out this line:
  //res.send('respond with a resource');

  // And insert something like this instead:
  res.json([
    {
      id: 1,
      username: "samsepi0l"
    },
    {
      id: 2,
      username: "D0loresH4ze"
    }
  ]);
});

module.exports = router;

Answer №1

While your implementation appears to be accurate, there seems to be a mistake in the request.

Make sure that your React component is requesting from http://localhost:3001/ or adjust your Express endpoint to router.get('/users', ....

Answer №2

When attempting to fetch data from express, you are trying to access the route /users, but your express code is not configured to handle this request. To resolve this issue, you should include a

router.get("/users", function(req, res, next) { }
in your Express app. It does not seem necessary to send JSX components (or maybe you meant data) back to react through a request. Can you provide more details about the specific problem you are facing?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Contrasts Between Two Methods for Developing a Dictionary-Like Class

What makes Code A/B unique and advantageous over one another? I will be requiring numerous classes to define entities in such a way that I can retrieve individual fields just like accessing class attributes Rather than plain json, I can identify the type ...

react-map-gl Popover not displaying when hovering in a React application

I've integrated react-map-gl into my Next.js application to display a Mapbox map. My goal is to have a popover appear when the user hovers over a line segment on the map. Below is the code snippet I'm using: import React from "react"; i ...

Guide to capturing user input in an Express router after it has been initialized

I currently have the following components in my project: - An app.js file that utilizes the routes specified in index.js - An index.js file where the initial SQL data retrieval is performed - An index.pug file containing a form to collect user input, in ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Testing React applications with Redux Toolkit using the React Testing Library

Currently, I am utilizing the Redux Toolkit approach by developing slices with reducer and extra reducers as well as thunks with createAsyncThunk API. As I delve into testing, I am eager to unveil the most effective way to test these components using React ...

Error: Unable to access undefined properties (specifically 'create') while using Sequelize in an Express.js and Node.js environment

Below is the snippet of my code Project Structure backendstuff (the express app) - models/currentweather.js - models/sequelize.js - routes/weather.js app.js models/currentweather.js const { Sequelize, DataTypes, Model } = require('sequelize'); ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

The issue of text decoration not applying to MUI list items

I've been using mui lists to set up a sidebar. <List> <StyledLink to="/"> <ListItem disablePadding> <ListItemButton> <ListItemIcon> <Grid ...

Unlawful use of Unicode characters

I am currently experiencing an issue while attempting to upload the document.sdf (json) file to Amazon Cloud Search. Everything works seamlessly until certain special characters are encountered. Encountered Unicode characters that are not compliant with C ...

What is the process for managing data synchronization in Redux-persist?

I developed an authorization application that writes data to AsyncStorage after a successful login. I now want to access this data through shared storage and am wondering how I can transfer or remove data synchronization with Redux-persist. ...

What is the most effective method for dimming or disabling a Material-UI div?

Within my application, there are instances where I need to dim and disable the mouse events for certain div elements based on the component's state - such as when it's loading. My initial approach involved creating a helper function that generate ...

Having trouble with the containerElement in React material-ui's MenuItem component?

I'm having an issue with the code below: <MenuItem primaryText="home" containerElement={<Link to="/" />} /> Despite following discussions on other platforms like this one Material UI Menu using routes, adding the containerElement prop to ...

Error message: The context object is not iterable. Please note that it must be iterable in order to avoid

While going through a React course on Context API, I encountered an error that says "context is not iterable TypeError: context is not iterable". Has there been any new syntax introduced? If so, please let me know. Here is the content of app.js: I'v ...

Managing headers for localhost with Access-Control-Allow-Origin

I've run into a challenge with my React app. I'm making endpoint calls to different servers and have withCredentials set to true to include a token/cookie in the requests. The issue arises when trying to make this work seamlessly on localhost. S ...

Images on Heroku vanish with each new push

Seeking Assistance! I recently deployed my nodejs backend app on Heroku, which involves a functionality where users can upload documents in jpg, jpeg, or png format. These documents are stored in the static folder (/assets/docs). Before pushing the updated ...

While working on a React Vite project, the ResponsiveAppBar.jsx component encountered an unexpected token error related to Material UI. Specifically, the issue stemmed from the code segment where a const handleOpenUser

I'm encountering an issue with my react+vite+material ui setup. When I attempt to implement the responsiveAppBar example, I run into errors. However, when I try the ButtonAppBar example from the same site, it works perfectly fine because the code is s ...

Errors occur when attempting to parse Uint8Array in Typescript

I received the following object as a response from calling the AWS Lambda client in NodeJS. { '$metadata': { httpStatusCode: 200, requestId: '1245', extendedRequestId: undefined, cfId: undefined, attempts: 1, tot ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

Leveraging Non-RESTful Requests in Loopback (Strongloop)

Our team is currently utilizing Loopback for our REST APIs and we are interested in incorporating some standard Node Express-like calls that won't be automatically routed through the Loopback framework. How can we add a new route without interfering w ...

Get rid of the port in Socket.IO and alter the directory

While utilizing Apache on Ubuntu 15.04, I am attempting to eliminate port 3000 from the URL and modify the path to http://example.com/{app}/socket.io... By employing ProxyPass and ProxyPassReverse, I have successfully removed the port from the URL and adj ...