0

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

我的项目中有这个:

代理/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)

然后在

包.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 有关,但我想我会提到它以防万一。

我在这里做错了什么?

4

1 回答 1

0

我终于让它工作了。

首先,我放弃了尝试让代理使用.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已经具有代理功能,只使用它并感到失败,即使我最终让它工作了。

于 2020-08-12T19:50:45.870 回答