2021年3月4日星期四

React is having trouble rendering elements when I serve the React from the same origin as express

I'm serving a React build from the same port (port 3000) that my express files receive requests on. Below is my code for doing so.

app.use(express.static(path.join(__dirname, "client", "build")))    app.get('/', (req, res) => {      res.sendFile(path.join(__dirname, "client", "build", "index.html"))  })  

In my react app, I make an API call to the server and the API's response updates the state. I know (from testing) that I'm getting the correct response from the server, and I know that the state is properly updated with the response. But when I try to render <p>{this.state.data}</p>, the entire app breaks and nothing is rendered.

Anyone have any ideas about why this is happening? I tried serving the React app from its folder on a different port and it still doesn't work. Posting all relevant code below for reference.

React Code

import React from 'react';  import './App.css';    class Form extends React.Component{    constructor(props){      super(props);    }      onTrigger = (event) => {      this.props.callBack();    }      render(){      return(            <div>                <form action="/photoupload" method="POST" className="" encType="multipart/form-data">                    <label for="species">Species Name:                         <input type="text" name="species" id="species"/>                    </label>                        <label for="description">Description:                         <textarea name="description" id="description" placeholder="Enter a description of your shroom..."></textarea>                    </label>                        <label for="photo">Photo:                         <input type="file" name="mushroom" id="mushroom" accept="image/*"/>                    </label>                        <input onClick={this.onTrigger} type="submit"/>                    </form>            </div>      )    }  }    class App extends React.Component {    constructor(props){      super(props);      this.state = {        data: ""      };    }      componentDidMount(){      fetch('/api', {method: "GET"})      .then(response => response.json())      .then(json => this.setState({        data: json      }))      console.log(this.state)    }      handleClick = () => {      console.log("Hello!")    }       render(){      return (        <div>          <Form callBack={this.handleClick} />          <p>{this.state.data}</p>        </div>      )    }  }    export default App;  

Server Code

const express = require('express')  const app = express();  const bodyParser = require('body-parser')  const multer = require('multer')  const upload = multer({dest: 'uploads/'})  const fs = require('fs')  const Mushroom = require('./db')  const path = require('path')  const cors = require('cors')    app.use(bodyParser.urlencoded({extended: false}));    app.use(express.static(path.join(__dirname, "client", "build")))    app.get('/', (req, res) => {      res.sendFile(path.join(__dirname, "client", "build", "index.html"))  })    app.get('/api', (req, res) => {      const mushroom = Mushroom.find({}, (err, docs) => {          res.send(docs)      });  })    app.post('/photoupload', upload.single('mushroom'), function (req, res) {      var mushroom = new Mushroom();      mushroom.species = req.body.species;      mushroom.description = req.body.description;      mushroom.path = req.file.path;      mushroom.save()      res.redirect("/")  })    app.listen(3000, () => {      console.log("listening on 3000!")  })  

EDIT

I'm just going to copy and paste the errors below:

App.js:51 Objectdata: "{_id: 132454}"__proto__: Object  :3000/manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found)  :3000/manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.  :3000/favicon.ico:1 Failed to load resource: the server responded with a status of 404 (Not Found)  react-dom.production.min.js:216 Error: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7B_id%2C%20age%2C%20species%2C%20description%2C%20path%2C%20__v%7D for the full message or use the non-minified dev environment for full errors and additional helpful warnings.      at ka (react-dom.production.min.js:140)      at d (react-dom.production.min.js:144)      at m (react-dom.production.min.js:146)      at react-dom.production.min.js:150      at Do (react-dom.production.min.js:176)      at Hu (react-dom.production.min.js:271)      at Pi (react-dom.production.min.js:250)      at xi (react-dom.production.min.js:250)      at _i (react-dom.production.min.js:250)      at vi (react-dom.production.min.js:243)  uu @ react-dom.production.min.js:216  react-dom.production.min.js:140 Uncaught (in promise) Error: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7B_id%2C%20age%2C%20species%2C%20description%2C%20path%2C%20__v%7D for the full message or use the non-minified dev environment for full errors and additional helpful warnings.      at ka (react-dom.production.min.js:140)      at d (react-dom.production.min.js:144)      at m (react-dom.production.min.js:146)      at react-dom.production.min.js:150      at Do (react-dom.production.min.js:176)      at Hu (react-dom.production.min.js:271)      at Pi (react-dom.production.min.js:250)      at xi (react-dom.production.min.js:250)      at _i (react-dom.production.min.js:250)      at vi (react-dom.production.min.js:243)  
https://stackoverflow.com/questions/66484909/react-is-having-trouble-rendering-elements-when-i-serve-the-react-from-the-same March 05, 2021 at 08:14AM

没有评论:

发表评论