【问题标题】:Why is webpack dev server not starting up my express server?为什么 webpack 开发服务器没有启动我的 express 服务器?
【发布时间】:2019-09-18 14:44:17
【问题描述】:

我正在使用 express 和 react 构建一个简单的网络应用程序。我通过我的 express 服务器为整个前端 React 包提供服务。

目前我的启动脚本运行良好,它构建前端代码并启动我的快速服务器。当我在浏览器中导航到应用程序时,一切正常,前端和后端都可以找到。但是,当我运行我的开发脚本时,我的后端端点不起作用,所以我收到错误并且前端永远不会呈现。

完整的源码可以在here找到,但我会把相关文件放在下面:

webpack.config.js:

module.exports = {
  mode: 'development',
  entry: './client/index.js',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
            loader: 'babel-loader',
            options: { 
              presets: ['@babel/preset-react']
            }
        }
      }, {
        test: /\.css$/,
        loader: 'style-loader'
        }, {
        test: /\.css$/,
  loader: 'css-loader',
  query: {
    modules: true,
    localIdentName: '[name]__[local]___[hash:base64:5]'
  }
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  output: {
    path: __dirname + '/dist',
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './dist'
  },
  devtool:"#eval-source-map"
};

package.json:

{
  "name": "contacts",
  "version": "1.0.0",
  "description": "A simple contacts app written using React, Node, and Mongo",
  "main": "index.js",
  "scripts": {
    "start": "npx webpack --mode=development && node server/server.js",
    "build": "webpack --mode=development",
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --config ./webpack.config.js --mode development"
  },
...

感谢您的帮助!

【问题讨论】:

    标签: javascript reactjs express webpack webpack-dev-server


    【解决方案1】:

    它在http://localhost:8080 上运行,但是,您有一个奇怪的实现,将整个ReactDOM.render 函数包装在一个promise 中。此外,如果缺少数据,则会导致 TypeError: this.props.contacts.map is not a function 并且不显示任何内容。

    API fetch 调用应该放在组件的 componentDidMount 生命周期内。那么class component 应该根据响应返回一些conditionally rendered 组件。您需要处理所有数据存在、数据丢失和/或 API 错误(否则会导致应用程序崩溃)的情况。

    工作 API 示例(具体看containers/Users/index.js 或下面写的示例代码):


    容器/用户/index.js

    import React, { Component } from "react";
    import app from "../../utils/axiosConfig";
    import ShowData from "../../components/ShowData";
    import ShowError from "../../components/ShowError";
    import ShowLoading from "../../components/ShowLoading";
    
    export default class App extends Component {
      state = {
        data: [],
        hasError: "",
        isLoading: true
      };
    
      componentDidMount = () => {
        window.setTimeout(() => {
          this.fetchData("users"); // calling "fetchData" after 1.5seconds (not necessary, but this way, you'll see a "Loading" component when data isn't present yet)
        }, 1500);
      };
    
      fetchData = url =>
        app
          .get(`${url}`) // makes a request to the API
          .then(res => { // handles a successful API response
            if (!res.data) throw new Error("No data was found!");
            this.setState({ isLoading: false, data: res.data });
          })
          .catch(err => // handles an API error or no data response
            this.setState({ isLoading: false, hasError: err.toString() })
          );
    
      handleClick = () => {
        this.setState({ isLoading: true, data: [] }, () => {
          this.fetchData("todos");
        });
      };
    
      // the code below utilizes a ternary operator: if cond ? then : else 
      // (shorthand for if/else or if/elseif/else ...etc)
      // the code below can be read as: if isLoading is true, then return
      // "<ShowLoading/>"; if it's false, but there was an error, then
      // return "<ShowError ... />", else if isLoading is false and 
      // hasError is false, then return "<ShowData ... />"
      render = () => (
        <div className="app-container">
          {this.state.isLoading ? (
            <ShowLoading />
          ) : this.state.hasError ? (
            <ShowError error={this.state.hasError} />
          ) : (
            <ShowData data={this.state.data} handleClick={this.handleClick} />
          )}
        </div>
      );
    }
    

    【讨论】:

    • 我明白您将 DOM 渲染函数包装在 promise 中的意思。我试图以这种方式为 redux 提供我的初始状态,当时感觉不对,我再也没有回去重新做。不过,这并不能真正解决我的问题,不是吗?我的快递服务器仍然没有在这些端点上提供任何服务
    • 我会将前端与后端分开。现在,您正尝试将两者托管在同一个端口上。相反,webpack-dev-server 应该在端口 3000 上提供服务,而您的 API 在端口 5000 上提供服务。编译后,所有内容都将在端口8080 上提供服务。使用concurrently,一个命令运行两个进程,例如:"concurrently \"npm run server\" \npm run dev --prefix client\"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 2018-07-17
    • 2015-02-17
    • 2014-06-26
    • 2017-05-12
    相关资源
    最近更新 更多