【问题标题】:Is there a way to proxy requests in Parcel as in Webpack?有没有办法像在 Webpack 中一样在 Parcel 中代理请求?
【发布时间】:2019-05-22 23:52:57
【问题描述】:

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

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

【问题讨论】:

标签: parceljs


【解决方案1】:

目前不直接支持这个,见open pull-requesthttps://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));

【讨论】:

  • 完美解析器!谢谢你,先生 !这是代理包裹的最佳方式!
【解决方案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 运行您的代理,以及默认的包裹命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 2023-03-08
    • 1970-01-01
    • 2019-08-16
    • 2022-10-25
    • 1970-01-01
    相关资源
    最近更新 更多