# Vercel 配置代理，让纯前端项目可以跨域请求

By [cryptoshine.eth](https://paragraph.com/@cryptoshine) · 2022-06-10

---

1.在根目录新建api文件夹，添加js文件做服务端代理
---------------------------

    const { createProxyMiddleware } = require('http-proxy-middleware')
    
    module.exports = (req, res) => {
        let target = ''
    
        // test路由的请求都会被转发到 www.test.net
        if (req.url.startsWith('/test')) {
            target = 'https://www.test.net/'
        }
    
        createProxyMiddleware({
            target,
            changeOrigin: true,
            pathRewrite: {
                // 路径重写，去掉test路径
                '^/test': '/'
            }
        })(req, res)
    }
    

2.在根目录新建vercel.json文件
---------------------

    {
        "headers": [
            {
                "source": "/(.*)",
                "headers": [
                    {
                        "key": "Access-Control-Allow-Origin",
                        "value": "*"
                    },
                    {
                        "key": "Access-Control-Allow-Headers",
                        "value": "content-type"
                    },
                    {
                        "key": "Access-Control-Allow-Methods",
                        "value": "DELETE,PUT,POST,GET,OPTIONS"
                    }
                ]
            }
        ],
        "rewrites": [
            {
                "source": "/test",
                "destination": "/api/proxy"
            }
        ]
    }
    

3.发布项目，完结。
----------

### 备注：可以在Functions下看到部署的代理

![](https://storage.googleapis.com/papyrus_images/e3b8b34f0227cf3cebd8849a1ad3b287d4fe14190889f5fe603651d7c7f68972.png)

---

*Originally published on [cryptoshine.eth](https://paragraph.com/@cryptoshine/vercel)*
