Why do I get TypeError when I try adding express to my first react app

随声附和 提交于 2020-01-06 08:16:09

问题


I have created my first react app using npx create-react-app my-app and started it. Now I want to add express into this react app. Hence I have added the below line in my index.js

var express = require('express')

Here is what my whole index.js looks like. The above is the only line that I have added, rest is exactly same as what I got from create-react-app

import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


var express = require('express')
// const helmet = require('helmet')
// const app = express()
// app.use(helmet())

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();

The error that I'm getting is TypeError: Unable to get property 'prototype' of undefined or null reference. The below is the full stacktrace of the error that I'm seeing in browser. And please note that there are no compilation issues.

×
TypeError: Unable to get property 'prototype' of undefined or null reference
Anonymous function
mylocaldrivepath/react/my-app/node_modules/express/lib/response.js:58
  55 |  */
  56 | 
  57 | 
> 58 | var res = Object.create(http.ServerResponse.prototype);
  59 | /**
  60 |  * Module exports.
  61 |  * @public
View compiled
./node_modules/express/lib/response.js
mylocaldrivepath/react/my-app/node_modules/express/lib/response.js:1
> 1 | /*!
  2 |  * express
  3 |  * Copyright(c) 2009-2013 TJ Holowaychuk
  4 |  * Copyright(c) 2014-2015 Douglas Christopher Wilson
View compiled
__webpack_require__
mylocaldrivepath/react/my-app/webpack/bootstrap:785
  782 | };
  783 | 
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^
  786 | 
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
mylocaldrivepath/react/my-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^
  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
./node_modules/express/lib/express.js
mylocaldrivepath/react/my-app/node_modules/express/lib/express.js:27
__webpack_require__
mylocaldrivepath/react/my-app/webpack/bootstrap:785
  782 | };
  783 | 
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^
  786 | 
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
mylocaldrivepath/react/my-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^
  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
./node_modules/express/index.js
mylocaldrivepath/react/my-app/node_modules/express/index.js:10
__webpack_require__
mylocaldrivepath/react/my-app/webpack/bootstrap:785
  782 | };
  783 | 
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^
  786 | 
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
mylocaldrivepath/react/my-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^
  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
./src/index.js
mylocaldrivepath/react/my-app/src/index.js:8
   5 | import * as serviceWorker from './serviceWorker';
   6 | 
   7 | 
>  8 | var express = require('express')
   9 | // const helmet = require('helmet')
  10 | 
  11 | // const app = express()
View compiled
__webpack_require__
mylocaldrivepath/react/my-app/webpack/bootstrap:785
  782 | };
  783 | 
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^
  786 | 
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
mylocaldrivepath/react/my-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^
  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
0
http://localhost:3000/static/js/main.chunk.js:388:1
__webpack_require__
mylocaldrivepath/react/my-app/webpack/bootstrap:785
  782 | };
  783 | 
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^
  786 | 
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
checkDeferredModules
mylocaldrivepath/react/my-app/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^
  46 |  }
  47 | }
  48 | 
View compiled
webpackJsonpCallback
mylocaldrivepath/react/my-app/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 | 
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^
  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
Global code
http://localhost:3000/static/js/main.chunk.js:1:2
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

Any help on fixing this issue is greatly appreciated !


回答1:


Typically express is placed outside of the src folder to serve your compiled client-side code; meanwhile, webpack-dev-server creates a development server and compiles code on the fly; so in this case, since you're using the create-react-app and not utilizing server-side rendering, then you don't need express (for development).

Instead, once you've compiled your code for production (via npm run build), you'll need some way to serve the assets. Typically, you'll have an app.js file that sits outside of the src folder and that will serve your compiled production folder (dist or build):

const { resolve } = require("path");
const express = require("express");

const app = express();
const currentDirectory = process.cwd(); // current directory

app.use(express.static("dist")); // express will serve up production assets
app.get("*", (req, res) =>
  res.sendFile(resolve(`${currentDirectory}/dist/index.html`))
); // express will serve up the front-end index.html file if it doesn't recognize the route

app.listen(8080, err => {
  if (!err) {
    console.log(`\nYour application is running on port 8080}\n`);
  } else {
    console.err(`\nUnable to start server: ${err}`);
  }
});

For example:

├── dist
|   ├── css
|   |   ├── main.[contenthash:8].css
|   |   └── main.[contenthash:8].css.map
|   ├── js
|   |   ├── main.[hash].js
|   |   └── main.[hash].js.map
|   ├── media
|   |   └── [hash].[ext]
|   └── favicon.ico
|   └── index.html
|
├── public
|   ├── favicon.ico
|   └── index.html
|
├── src
|   ├── actions
|   ├── components
|   ├── containers
|   ├── images
|   ├── pages
|   ├── reducers
|   ├── root
|   ├── routes
|   ├── styles
|   ├── types
|   ├── utils
|   └── index.js
|
└── app.js


来源:https://stackoverflow.com/questions/58263678/why-do-i-get-typeerror-when-i-try-adding-express-to-my-first-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!