简体   繁体   English

将 http-proxy-middleware 与 typescript 和跨环境一起使用

[英]Using http-proxy-middleware with typescript and cross-env

I am trying to set up a proxy for my React TypeScript app using http-proxy-middleware to prevent CORS errors while developing.我正在尝试使用http-proxy-middleware为我的 React TypeScript 应用程序设置代理,以防止开发时出现 CORS 错误。

I have this in my project:我的项目中有这个:

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

Then in然后在

package.json package.json

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

However when I run the script in the console I get this:但是,当我在控制台中运行脚本时,我得到了这个:

[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...

If I try adding type": "module" to packages.json then my actual app stops running with the error:如果我尝试将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.

I not even sure what "type" is used for and why its apparently needed in this case, so I don't really want to add random things without knowing what I'm doing.我什至不确定使用什么“类型”以及为什么在这种情况下显然需要它,所以我真的不想在不知道自己在做什么的情况下添加随机的东西。 It doesn't solve the problem anyway as I get a new error then when running the proxy:无论如何它都不能解决问题,因为我在运行代理时遇到了一个新错误:

$ 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...

Not sure if this has anything to do with TypeScript, but I thought I'd mention it just in case.不确定这是否与 TypeScript 有关,但我想我会提一下以防万一。

What am I doing wrong here?我在这里做错了什么?

I finally got it working.我终于让它工作了。

First of all I gave up on trying to get the proxy to work with a .txs filetype.首先,我放弃了尝试让代理使用.txs文件类型。 So I went with .js and also used require(... ) instead of import所以我选择了.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)

Then I realized that this all makes no sense, because if I made a query to ./api it would direct it to the actual apps port, which is port 3001, because that is where my actual app is running at.然后我意识到这一切都没有意义,因为如果我对./api进行查询,它会将其定向到实际的应用程序端口,即端口 3001,因为这是我的实际应用程序运行的地方。

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

Making a direct call to port 3002 resulted in a failure and running them both on 3001 stopped my app from working altogether.直接调用端口 3002 导致失败,并且在 3001 上运行它们使我的应用程序完全无法工作。 So the solution was to add this to webpack.config.js :所以解决方案是将其添加到webpack.config.js

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

Now hold on a second here.现在在这里稍等。 Why am I doing this?我为什么要这样做? Why not just target port 8080 right away here any bypass that proxy.js totally... and what do you know.为什么不直接针对端口 8080 完全绕过proxy.js ......你知道什么。 It works.有用。 All I had to do was add我所要做的就是添加

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

to webpack.config.js .webpack.config.js

And with that I concede that I have absolutely no idea what I am doing and all of this stuff is very confusing, error-prone and complicated.我承认我完全不知道我在做什么,所有这些东西都非常混乱、容易出错和复杂。 I was able to remove express and http-middleware-proxy from my dependencies (the dev server seems to get them on their own).我能够从我的依赖项中删除expresshttp-middleware-proxy (开发服务器似乎自己获取它们)。

In conclusion I gave up trying to set up my own express proxy, realized that apparently webpack-dev-server already has proxy capabilities, resorted to just using that and left feeling defeated even though I got it working in the end.总之,我放弃了尝试建立自己的快速代理,意识到显然webpack-dev-server已经具有代理功能,只使用它并感到失败,即使我最终让它工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM