装置插件
npm i -D http-proxy-middleware
在你前端工程根目录中创立以下两个文件
api/proxy.js
// api/proxy.js
// 该服务为 vercel serve跨域解决
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = (req, res) => {
let target = ''
// 代理指标地址
// 这里应用 backend 次要用于辨别 vercel serverless 的 api 门路
// target 替换为你跨域申请的服务器 如: http://baidu.com
if (req.url.startsWith('/backend')) {
target = 'https://fanyi-api.baidu.com'
}
// 创立代理对象并转发申请
createProxyMiddleware({
target,
changeOrigin: true,
pathRewrite: {
// 通过门路重写,去除申请门路中的 `/backend`
// 例如 /backend/user/login 将被转发到 https://fanyi-api.baidu.com/user/login
'^/backend/': '/',
},
})(req, res)
}
vercel.json 文件
{
"rewrites": [
{
"source": "/backend/(.*)", // 筹备匹配的接口
"destination": "/api/proxy" // 配置门路
}
]
}
http接口申请代码前缀记得换成/backend/
代码提交,默认主动部署到vercel了
设置vercel
1、关上我的项目,点击 Functions
2、抉择api/proxy.js文件
发表回复