简体   繁体   English

在 express 应用中配置代理中间件

[英]Configuring proxy middleware in express app

My application consists of a frontend server (React, serve as static) and backend server (Express).我的应用程序由前端服务器(React,作为静态服务器)和后端服务器(Express)组成。 I found that whenever I am sending requests with custom headers, a preflight request will be sent.我发现每当我发送带有自定义标头的请求时,都会发送一个预检请求。 This increases the latency of my application.这增加了我的应用程序的延迟。 I would like to avoid those preflight requests.我想避免那些预检请求。

For example,例如,

frontend: example.web.com前端:example.web.com

backend: example.api.com后端:example.api.com

One approach found is to setup proxy middleware in my backend so that the requests will be sent from backend server to backend server instead of frontend (browser) to backend.找到的一种方法是在我的后端设置代理中间件,以便将请求从后端服务器发送到后端服务器,而不是从前端(浏览器)发送到后端。

const proxy = require('http-proxy-middleware');
const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors({
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    allowedHeaders: "authorization",
}));
let options = {
    target: 'http://localhost:5001/',
    changeOrigin: true,
    logLevel: 'debug',
    onError: function onError(err, req, res) {
        console.log('Something went wrong with the proxy middleware.', err)
        res.end();
    }
};
app.use("/", proxy(options), indexRouter);

What I expected to avoid preflight requests when sending not "simple" requests.我希望在发送非“简单”请求时避免预检请求。 I knew that proxy middleware approach can avoid preflight requests, but I do not know the right way to configure in my Express application.我知道代理中间件方法可以避免预检请求,但我不知道在我的 Express 应用程序中配置的正确方法。

http-proxy-middleware will send you the responses it gets from the target api server. http-proxy-middleware 将向您发送它从目标 api 服务器获得的响应。 it does not move on to the next middleware, though.但是,它并没有转移到下一个中间件。

app.use("/", proxy(options)) means any request to your server will be proxied to the target api: a request to yourserver.com/items will be proxied to targetapi.com/items . app.use("/", proxy(options))意味着对您服务器的任何请求都将被代理到目标 api:对yourserver.com/items的请求将被代理到targetapi.com/items If you want to be able to have your own routes, either use a prefix for the middleware ( app.use("/api", proxy(options)) ) or mount those other middlewares before the proxy.如果您希望能够拥有自己的路由,请使用中间件的前缀( app.use("/api", proxy(options)) )或在代理之前安装其他中间件。

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

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