# Vercel 配置代理,让纯前端项目可以跨域请求 **Published by:** [cryptoshine.eth](https://paragraph.com/@cryptoshine/) **Published on:** 2022-06-10 **URL:** https://paragraph.com/@cryptoshine/vercel ## Content 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下看到部署的代理 ## Publication Information - [cryptoshine.eth](https://paragraph.com/@cryptoshine/): Publication homepage - [All Posts](https://paragraph.com/@cryptoshine/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@cryptoshine): Subscribe to updates