为什么我们需要在express.js服务器上使用代理,以便将webpack热重新加载服务器功能与反应路由相结合 [英] Why do we need a proxy on an express.js server in order to get webpack hot reloading server functionality combined with react-routing

查看:217
本文介绍了为什么我们需要在express.js服务器上使用代理,以便将webpack热重新加载服务器功能与反应路由相结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可选信息:我试图使这个项目 marty.js webpack dev server 允许反应路由器,所以它不仅仅是\路径。



因此,我正在学习这个IIS堆栈溢出回答一整天,我不明白



>

我设置了一个代理来实现这一点:



你有一个正常的快速网络服务器,服务于ind任何>路线上的ex.html,除非是资产路线。如果它是资产,则该请求被代理到web-dev-server



您的反应热入点仍将直接指向webpack dev服务器,因此热重新加载仍然



让我们假设你在8081上运行webpack-dev-server,你的代理在8080.


我的代码现在看起来像这样,但为了使其工作,我将来需要实现。为了实现,我必须先了解retonzis的答案。



express.js文件



要求 / p>

 'use strict'; 
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var config = require('../ config.json');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var proxy = require('proxy-middleware');
var url = require('url');

代理

  var app = express(); //我们的表达式

// --------我的代理----------------------


app.use('/ assets',proxy(url.parse('http:// localhost:8081 / assets'))); //但是为什么我们需要一个代理?这条线真的让我感到困惑。

marty-express **



我计划在我明白这个例子之后使用这个权限,我只是希望它通过反应路由到快递。**

 code> //app.use(request('marty-express')({
// routes:require('../ routes'),
// application:require(' ../application').Application
//}));

表达东西

  app.get('/ *',function(req,res){
res.sendFile(__ dirname +'/index.html');
}); //如果我直线这一行直接告诉服务器我的index.html文件到所有路由。我的猜测是在我实现[marty-express] [4]时会被删除。

2个服务器webpack-dev-server和express

  // ----- my-webpack-dev-server ---------------- -  
var webpackServer = new WebpackDevServer(webpack(require('../../ webpack.config')),{
contentBase:__dirname,
hot:true,
安静:false,
noInfo:false,
publicPath:'/ assets /',
stats:{colors:true}
});

//在端口8081上运行webpack热重载服务器
webpackServer.listen(8081,'localhost',function(){});

//在端口8080上运行快速服务器
app.listen(8080);

昨天有没有人可以向我解释这个consept,就像我从火星上下来的?



我无法理解2件事:


  1. 为什么我们需要代理

  2. 如何将反应路由传递给express,以便在询问时在每个路由上提供它们。
    (可能
    marty-express 可以帮助我们完成这项任务,但我的猜测是我们可以手动做没有它)

Bah ...帮助我摆脱这个文档稀缺HELL !请你慷慨地回答你的答案..
记住,我刚刚来自火星昨天。



谢谢..!

解决方案

你不是,但它很棘手。所以第一个要求是你有一个可配置的资产根。如果您将来需要CDN,这也是值得的。假设这是一个envvar ASSET_URL,它可以在运行webpack dev服务器和快速服务器时使用。



你需要通常的webpack dev服务器,加上CORS头。这使您的主要快递服务器只是在脚本/链接标签中指向webpack dev服务器。



ASSET_URL如下: http:// localhost:8081



Webpack





  var config =要求( './ webpack.config'); 

var port ='8081',hostname ='localhost';

if(process.env.ASSETS_URL){
var assetsUrlParts = url.parse(process.env.ASSETS_URL);
port = assetUrlParts.port;
hostname = assetUrlParts.hostname;
}

new WebpackDevServer(webpack(serverConfig),{
publicPath:serverConfig.output.publicPath,
hot:true,
headers:{访问控制允许原点:*}
})。listen(port,'localhost',function(err,result){
if(err){
console log(err);
process.exit(1);
}

console.log('Listening at'+ url.format({port:port,hostname:hostname ,protocol:'http:'}));
});

然后在您的webpack配置文件中,你有大部分相同的垃圾。

  var port ='8081',hostname ='localhost'; 

if(process.env.ASSETS_URL){
var assetsUrlParts = url.parse(process.env.ASSETS_URL);
port = assetUrlParts.port;
hostname = assetUrlParts.hostname;
}

...

条目:[
'webpack-dev-server / client?'+ url.format({port:port ,hostname:hostname,protocol:'http:'}),
'webpack / hot / only-dev-server',
...

输出:{
path:__dirname +'/ public /',
filename:'bundle.js',
publicPath:process.env.ASSETS_URL || '/ public /'



Express Server



这里唯一的特别之处在于,您需要以某种方式将 process.env.ASSETS_URL 加入模板的本地。

 < HEAD> 
< link rel =stylesheethref ={{assetsUrl}} / main.css>
< / head>
< body>
...
< script type =text / javascriptsrc ={{assetsUrl}} / bundle.js>< / script
< / body>


Optional info: I'm trying to make this project built with marty.js and webpack dev server allow entry points from react-router so that it works in more than just the \ path.

Thus, I'm studying THIS stack overflow answer all day long and I fail to understand the logic behind the following code and why this answer works.

retozi answered:

I set up a proxy to achieve this:

You have a regular express webserver that serves the index.html on any > route, except if its an asset route. if it is an asset, the request gets proxied to the web-dev-server

your react hot entrypoints will still point directly at the webpack dev server, so hot reloading still works.

Let's assume you run webpack-dev-server on 8081 and your proxy at 8080.

My code looks like this now, but in order to make it work I will later on need to implement marty-express. In order to implement that I must first understand retonzis answer.

express.js file

requirements

    'use strict';
    var express = require('express');
    var path = require('path');
    var logger = require('morgan');
    var bodyParser = require('body-parser');
    var config = require('../config.json');
    var webpack = require('webpack');
    var WebpackDevServer = require('webpack-dev-server');
    var proxy = require('proxy-middleware');
    var url = require('url');

proxy

    var app = express(); //our express instance

    // -------- my proxy----------------------


    app.use('/assets', proxy(url.parse('http://localhost:8081/assets')));//but why do we need a proxy? This line really confuses me.

marty-express **

I plan to use that right after I understand this example, I just HOPE it passes react-routes into express.**

    //app.use(require('marty-express')({
    //    routes: require('../routes'),
    //    application: require('../application').Application
    //}));

express stuff

    app.get('/*', function(req, res) {
        res.sendFile(__dirname + '/index.html');
    });//if I got this straight this line just tells express to server my index.html file to all routes. My guess is this will be removed when I implement [marty-express][4].

the 2 servers webpack-dev-server and express

        //----- my-webpack-dev-server------------------
    var webpackServer = new WebpackDevServer(webpack(require('../../webpack.config')), {
        contentBase: __dirname,
        hot: true,
        quiet: false,
        noInfo: false,
        publicPath: '/assets/',
        stats: { colors: true }
    });

    //run webpack hot reload server on port 8081
    webpackServer.listen(8081, 'localhost', function() {});

    //run express server on port 8080
    app.listen(8080);

Could someone be kind enough to explain to me this consept like I came down from planet Mars yesterday?

I fail to understand 2 things:

  1. Why we need a proxy
  2. How to pass react-routes into express so that it serves them on each route when asked. (pehaps marty-express helps us with that task, but my guess is we could do that manually without it)

Bah... Help me get out of this Documentation scarcity HELL!!! and please be generous in your answer.. Remember, I just came from Mars yesterday.

Thank you..!

解决方案

You don't, but it's tricky. So the first requirement is that you have a configurable asset root. This also pays off if you need a CDN in the future. Let's say this is in an envvar ASSET_URL which is available both when running your webpack dev server and your express server.

You need the usual webpack dev server, plus the CORS header. This lets your main express server just point to the webpack dev server in the script/link tags.

ASSET_URL is like: http://localhost:8081

Webpack

var config = require('./webpack.config');

var port = '8081', hostname = 'localhost';

if (process.env.ASSETS_URL) {
    var assetUrlParts = url.parse(process.env.ASSETS_URL);
    port = assetUrlParts.port;
    hostname = assetUrlParts.hostname;
}

new WebpackDevServer(webpack(serverConfig), {
  publicPath: serverConfig.output.publicPath,
  hot: true,
  headers: { "Access-Control-Allow-Origin": "*" }
}).listen(port, 'localhost', function (err, result) {
  if (err) {
    console.log(err);
    process.exit(1);
  }

  console.log('Listening at ' + url.format({port: port, hostname: hostname, protocol: 'http:'}));
});

Then in your webpack config file you have most of the same junk.

var port = '8081', hostname = 'localhost';

if (process.env.ASSETS_URL) {
    var assetUrlParts = url.parse(process.env.ASSETS_URL);
    port = assetUrlParts.port;
    hostname = assetUrlParts.hostname;
}

...

  entry: [
    'webpack-dev-server/client?' + url.format({port: port, hostname: hostname, protocol: 'http:'}),
    'webpack/hot/only-dev-server',
    ...

  output: {
    path: __dirname + '/public/',
    filename: 'bundle.js',
    publicPath: process.env.ASSETS_URL || '/public/'

Express Server

The only special thing here is you need to somehow get process.env.ASSETS_URL into the locals of your templates.

<head>
    <link rel="stylesheet" href="{{ assetsUrl }}/main.css">
</head>
<body>
    ...
    <script type="text/javascript" src="{{ assetsUrl }}/bundle.js"></script
</body>

这篇关于为什么我们需要在express.js服务器上使用代理,以便将webpack热重新加载服务器功能与反应路由相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆