7

在 Webpack 中,可以通过proxy配置文件中的设置来代理后端请求。这允许我使用带有 HMR 的 webpack-dev-server 开发我的应用程序的前端部分,而 webpack-dev-server 和我的应用程序服务器在我的本地主机上的不同端口上运行。Parcel 中还有一个开发服务器,默认命令parcel index.html在端口 1234 上运行。有没有办法同时运行 Parcel 开发服务器和对我的应用服务器的代理请求?

我找到了一个建议为此使用 Express 中间件的解决方案。但这并不能完全干净地解决问题。如果我的后端运行 Django 怎么办?那么我应该如何使用 Parcel 开发服务器呢?

4

2 回答 2

5

目前不直接支持这个,看open pull-request https://github.com/parcel-bundler/parcel/pull/2477

但是,https://github.com/parcel-bundler/parcel/issues/55并列出了涉及简单包装器的各种解决方案,例如:

对于http-proxy-middleware>= 1.0.0(2020 年 2 月发布):

const Bundler = require('parcel-bundler');
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');


const app = express();

app.use(createProxyMiddleware('/api', {
  target: 'http://localhost:3000'
}));

const bundler = new Bundler('src/index.html');
app.use(bundler.middleware());

app.listen(Number(process.env.PORT || 1234));

对于旧http-proxy-middleware版本(版本 0.x):

const Bundler = require('parcel-bundler');
const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();

app.use('/api', proxy({
  target: 'http://localhost:3000/api'
}));

const bundler = new Bundler('src/index.html');
app.use(bundler.middleware());

app.listen(Number(process.env.PORT || 1234));

于 2019-05-22T10:34:20.343 回答
2

有一个名为parcel-proxy-server的 npm 模块可能会有所帮助。我自己尝试过,它对我的​​项目非常有效。

从文档中:创建一个文件,例如server.js

const ParcelProxyServer = require('parcel-proxy-server');

// configure the proxy server
const server = new ParcelProxyServer({
  entryPoint: './path/to/my/entry/point',
  parcelOptions: {
    // provide parcel options here
    // these are directly passed into the
    // parcel bundler
    //
    // More info on supported options are documented at
    // https://parceljs.org/api
    https: true
  },
  proxies: {
    // add proxies here
    '/api': {
      target: 'https://example.com/api'
    }
  }
});

// the underlying parcel bundler is exposed on the server
// and can be used if needed
server.bundler.on('buildEnd', () => {
  console.log('Build completed!');
});

// start up the server
server.listen(8080, () => {
  console.log('Parcel proxy server has started');
});

然后调用node server.js运行您的代理,以及默认的包裹命令。

于 2019-07-22T21:14:21.500 回答