Create Proxy Server
Creating and deploying a tiny proxy server on Vercel in 10 minutes · mmazzarolo.com
项目设置
1mkdir my-proxy && cd my-proxy
2npm init
3npm install -D vercel
4mkdir api && touch api/index.js
5touch vercel.json
my-proxy/package.json
1{
2 "name": "my-proxy",
3 "version": "1.0.0",
4 "scripts": {
5+ "start": "vercel dev"
6 },
7}
Vercel serverless functions use a file-system-based convention. So the
api/index.js
file you just created will automatically handle all requests of the/api
endpoint:
my-proxy/api/index.js
1// In Vercel, any file inside the "api" directory is exposed on an "/api" endpoint.
2// For an API route to work, you need to export a function as default (a.k.a request handler),
3// which then receives the following parameters:
4// - req: The request object.
5// - res: The response object.
6// See https://vercel.com/docs/serverless-functions/supported-languages#node.js for details.
7export default async function handler(req, res) {
8 res.status(200).send(`Hello world!`)
9}
my-proxy/vercel.json
1{
2 "rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
3}
代理逻辑设置
1npm i http-proxy-middleware
修改 my-proxy/api/index.js
1// Create a proxy to redirect requests of the "/api/*" path to "https://example.org".
2//
3// Examples:
4// GET /api/hello → GET https://example.org/hello
5// POST /api/test?color=red → POST https://example.org/test?color=red
6//
7// Additionally, the proxy will:
8// - Add an "x-added" header
9// - Remove the "x-removed" header
10// From the proxied response.
11//
12// You can/should update the proxy to suit your needs.
13// See https://github.com/chimurai/http-proxy-middleware for more details.
14const { createProxyMiddleware } = require('http-proxy-middleware')
15const apiProxy = createProxyMiddleware({
16 target: 'https://example.org',
17 changeOrigin: true,
18 pathRewrite: {
19 '^/api': '', // strip "/api" from the URL
20 },
21 onProxyRes(proxyRes) {
22 proxyRes.headers['x-added'] = 'foobar' // add new header to response
23 delete proxyRes.headers['x-removed'] // remove header from response
24 },
25})
26// Expose the proxy on the "/api/*" endpoint.
27export default function (req, res) {
28 return apiProxy(req, res)
29}