【问题标题】:Setting up React on the front end and Express.js as a server with Webpack 4使用 Webpack 4 在前端设置 React 和 Express.js 作为服务器
【发布时间】:2018-08-23 17:03:46
【问题描述】:

现在我已经完成了关于 React 和 webpack 的所有工作:

这是我的webpack.config.js

const HtmlWebPackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  entry: {
    index: './client/index.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, 'public'),
  },
  devServer: {
    contentBase: path.join(__dirname, 'public'),
    port: 3000,
  },

 /* module info */
  ......
 /* module info */

 plugins: [
    new HtmlWebPackPlugin({
      filename: './index.html',
      template: './src/index.html',
    }),
  ],
};

当运行 npm run dev 时,这会启动 localhost:3000 上的 webpack-dev-server \o/

现在我还想使用express 来提供来自路由或 api 的数据,并在前端做出反应并对其进行调用。

我的 Express 设置:

const express = require('express');
const app = express();
const path = require('path');

app.set('port', process.env.PORT || 8016);

const issues = [
  {
    id: 1,
    status: 'Open',
    owner: 'Ravan',
    created: new Date('2016-08-15'),
    effort: 5,
    completionDate: undefined,
  },
  {
    id: 3,
    status: 'Assigned',
    owner: 'Eddie',
    created: new Date('2016-08-16'),
    effort: 14,
    completionDate: new Date('2016-08-30'),
    title: 'Missing bottom border on panel',
  },
]; // global data

app.use(express.static(path.join(__dirname, '..', 'public')));

app.get('/api/issues', (req, res) => {
  var metadata = { total_count: issues.length };
  res.json({ _metadata: metadata, records: issues });
});

// sends index.html
app.use('*', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'public/index.html'));
});

app.listen(app.get('port'), function(error) {
  console.log(`App started on port ${app.get('port')}!`);
});

module.exports = app;

所以你可以看到 express 将在http://localhost:8016 上运行 并对http://localhost:3000做出反应。有没有办法让它们在同一个端口上运行?如果不是,您能解释一下原因吗?

提前致谢!

【问题讨论】:

  • 明确地说,您要问的是当客户从快递服务时如何让热重载工作?
  • @Samo 我实际上改写了它,上面!

标签: reactjs express webpack


【解决方案1】:

这是不可能的,因为您不能在同一个端口上运行两台服务器(如果可能的话,我还没有这方面的知识:P)。

向您的 api 发出请求的方法是设置 devServer 的代理选项:

devServer: {
  contentBase: resolve(__dirname, 'public'),
  clientLogLevel: 'warning',
  historyApiFallback: true,
  host: '0.0.0.0',
  hot: true,
  port: 3000,
  proxy: {
    '/api/*': 'http://localhost:8016'
  }

现在你可以通过 react 发出这样的请求:

axios.get('/api/issues').then((res) => { console.log(res.data) })

您可以查看文档here。

【讨论】:

  • 谢谢我的朋友!所以理论上,你会在生产中做同样的事情吗?
猜你喜欢
  • 2019-12-20
  • 2016-06-15
  • 2018-02-02
  • 2018-07-23
  • 2022-01-19
  • 2018-04-04
  • 2019-03-27
  • 1970-01-01
  • 2016-12-20
相关资源
最近更新 更多