【问题标题】:Using http-proxy-middleware with typescript and cross-env将 http-proxy-middleware 与 typescript 和 cross-env 一起使用
【发布时间】:2020-08-11 21:40:16
【问题描述】:

我正在尝试使用 http-proxy-middleware 为我的 React TypeScript 应用设置代理,以防止开发时出现 CORS 错误。

我的项目中有这个:

proxy/proxy.tsx

import * as express from 'express'
import { createProxyMiddleware } from 'http-proxy-middleware'

const app = express()

app.use('/api', createProxyMiddleware({ target: 'localhost:8080', changeOrigin: true }))
app.listen(3000)

然后在

package.json

"main": "src/index.tsx",
"scripts": {
  ...
  "proxy": "cross-env nodemon proxy/proxy",
  ...
},

但是,当我在控制台中运行脚本时,我得到了这个:

[nodemon] starting `node proxy/proxy src/index.tsx`
(node:28564) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
C:\*path to project*\pet-project-fe\src\index.tsx:1
import React from 'react'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

如果我尝试将 type": "module" 添加到 packages.json 中,那么我的实际应用程序将停止运行并出现错误:

"C:\Program Files\nodejs\node.exe" C:\*path to npm*\npm\node_modules\yarn\bin\yarn.js run start
yarn run v1.22.4
$ cross-env NODE_ENV=development webpack-dev-server --open --content-base ./public --port 3001
internal/modules/cjs/loader.js:1153
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\*path to project*\pet-project-fe\webpack.config.js
require() of ES modules is not supported.
require() of C:\*path to project*\pet-project-fe\webpack.config.js from C:\*path to project*\pet-project-fe\node_modules\webpack-cli
\bin\utils\convert-argv.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines
all .js files in that package scope as ES modules.
Instead rename webpack.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\*path to project*\pet-project-fe\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:13)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at WEBPACK_OPTIONS (C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:114:13)
    at requireConfig (C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:116:6)
    at C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:123:17
    at Array.forEach (<anonymous>)
    at module.exports (C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:121:15) {
  code: 'ERR_REQUIRE_ESM'
}
error Command failed with exit code 1.

我什至不确定“类型”的用途以及为什么在这种情况下显然需要它,所以我真的不想在不知道自己在做什么的情况下添加随机的东西。无论如何,它并没有解决问题,因为我在运行代理时遇到了一个新错误:

$ cross-env nodemon proxy/proxy
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: tsx,json
[nodemon] starting `node proxy/proxy src/index.tsx`
(node:25420) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                              ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".tsx" for C:\*path to project*\pet-project-fe\src\index.tsx
    at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
    at Loader.getFormat (internal/modules/esm/loader.js:113:42)
    at Loader.getModuleJob (internal/modules/esm/loader.js:244:31)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Loader.import (internal/modules/esm/loader.js:178:17) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
[nodemon] app crashed - waiting for file changes before starting...

不确定这是否与 TypeScript 有关,但我想我会提到它以防万一。

我在这里做错了什么?

【问题讨论】:

    标签: reactjs typescript express http-proxy-middleware cross-env


    【解决方案1】:

    我终于搞定了。

    首先,我放弃了让代理使用.txs 文件类型的尝试。所以我选择了.js 并且还使用了require(...) 而不是import

    const express = require('express')
    const { createProxyMiddleware } = require('http-proxy-middleware')
    
    const app = express()
        
    app.use('/api/**', createProxyMiddleware({ target: 'http://localhost:8080', changeOrigin: true }))
    app.listen(3002)
    

    然后我意识到这一切毫无意义,因为如果我向./api 进行查询,它会将其定向到实际的应用程序端口,即端口 3001,因为那是我的实际应用程序运行的位置。

    "start": "cross-env NODE_ENV=development webpack-dev-server --open --content-base ./public --port 3001",
    

    直接调用端口 3002 导致失败,并且在 3001 上同时运行它们使我的应用程序完全无法工作。所以解决方案是将其添加到webpack.config.js:

    config.devServer = {
      ...
      proxy: [{
        context: ['/api'],
        target: `http://localhost:3002`,
        changeOrigin: true,
      }],
    };
    

    现在请稍等。我为什么要这样做?为什么不直接针对端口 8080 直接绕过 proxy.js 完全......你知道什么。有用。我所要做的就是添加

    config.devServer = {
      ...
      proxy: [{
        context: ['/api'],
        target: `http://localhost:8080`,
        changeOrigin: true,
      }],
    };
    

    到webpack.config.js。

    因此,我承认我完全不知道自己在做什么,所有这些东西都非常令人困惑、容易出错和复杂。我能够从我的依赖项中删除 express 和 http-middleware-proxy(开发服务器似乎自己获取它们)。

    最后我放弃了尝试建立自己的快速代理,意识到显然webpack-dev-server 已经具有代理功能,只使用它并感到失败,即使我最终让它工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-05
      • 2019-06-14
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2020-03-26
      相关资源
      最近更新 更多