---
title: "node.js中间件代理服务器跨域"
id: "3099"
type: "post"
slug: "node-js%e4%b8%ad%e9%97%b4%e4%bb%b6%e4%bb%a3%e7%90%86%e6%9c%8d%e5%8a%a1%e5%99%a8%e8%b7%a8%e5%9f%9f"
published_at: "2020-07-07T06:39:55+00:00"
modified_at: "2020-07-07T07:03:44+00:00"
url: "https://seq.ink/all/3099.html"
markdown_url: "https://seq.ink/all/3099.html.md"
excerpt: "const express = require(\"express\"); const { createProxyMiddleware } = require(\"http-proxy-middleware\"); const app = expr ..."
taxonomy_category:
  - "ALL"
---

```
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const app = express();
// 设置允许跨域响应头
app.all("*", function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

// http-proxy-middleware中间件
app.use(
  "/",
  createProxyMiddleware({
    target: "http://localhost:3000",
    changeOrigin: true
  })
);
app.listen(8080);
```

服务器3000端口，前端请求的是8080端口，产生了跨域行为u。使用中间件代理跨域服务器监听前端请求转发到服务器拿到结果随后把结果发送回客户端。
