vercel和netlify部署代码并解决接口代理转发的问题(和Nginx功能一样)

前言

  • 部署过程就不说了,部署完成后是这样子的

  • 然后访问链接,无法访问

解决

  • 依次点击 Settings–>Domains,在输入框中输入你的域名并点击 Add 按钮。

  • 以此域名为例子demo.gshopfront.dreamlove.top为例,点击添加

  • 我们前往域名管理系统,记录下绿色的值以腾讯云的为例

  • 上图中的Name对应的是主机记录,Value对应的是记录值,记录类型选择CNAME

  • 验证成功,vercel自动生成ssl证书当中

  • 访问成功

  • 例子http://demo.gshopfront.dreamlove.top/

vercel解决接口代理问题

  • 编译为静态文件后,代理转发没有了,跨域了,所以我们需要自己配置下代理转发给vercel使用

  • 一模一样添加完成https://segmentfault.com/a/1190000042276351?sort=newest

  • 安装开发依赖

npm i -D http-proxy-middleware
  • 目录建立vercel.json,注释记得删除
//注释记得删除
{
    
    
  "rewrites": [
    {
    
    
      "source": "/api/(.*)", //要匹配的路径前缀(我们本地访问的路径),结合自己的前缀设置
      "destination": "/api/proxy" //需要转发给哪一个目录下的配置
    }
  ]
}
  • 建立api/proxy.js文件
    • 注意: 由于这里的接口不需要pathRewrite,所以就删除了pathRewrite配置
      • 效果,当我们访问搭建好的目录https://demo.gshopfront.dreamlove.top/api/user的时候,就会被转发给http://gmall-h5-api.atguigu.cn/api/user
    • 如果需要去除掉api这个前缀,就把pathRewrite打开,
      • 效果:当我们访问搭建好的目录https://demo.gshopfront.dreamlove.top/api/user的时候,就会被转发给http://gmall-h5-api.atguigu.cn/user,(去除掉了api)
// api/proxy.js
// 该服务为 vercel serve跨域处理
const {
    
     createProxyMiddleware } = require('http-proxy-middleware')

module.exports = (req, res) => {
    
    
    let target = ''
    // 代理目标地址
    // 这里使用 backend 主要用于区分 vercel serverless 的 api 路径
    // target 替换为你跨域请求的服务器 如: http://gmall-h5-api.atguigu.cn
    if (req.url.startsWith('/api')) {
    
    
        target = 'http://gmall-h5-api.atguigu.cn'
    }
    // 创建代理对象并转发请求
    createProxyMiddleware({
    
    
        target,
        changeOrigin: true,
        pathRewrite: {
    
    
            // 通过路径重写,去除请求路径中的 `/api`
            // 如果开启了,那么 /api/user/login 将被转发到 http://gmall-h5-api.atguigu.cn/user/login
            //'^/api/': '/',
        },
    })(req, res)
}
  • 目录结构

  • 编辑好后推送,然后等待重新编译
  • 之后会出现此下拉栏目

  • 如果没有出现Functions栏目,就点击这里

  • 这样子也可以出现Function

  • 选择我们的api/proxy

  • 然后就可以正常啦

  • 如果部署遇到这种问题error @achrinza/[email protected]: The engine "node" is incompatible with this module. Expected version "8 || 10 || 12 || 14 || 16 || 17". Got "18.13.0"

  • 发现vercel设置node版本后重新部署也不行,不知道为什么,…

netlify解决接口代理问题

  • 建立netlify.toml文件
[[redirects]]
  from = "/prod-api/*"
  to = "http://gmall-h5-api.atguigu.cn/:splat"
  status = 200
  • 在netlify网站请求接口如果使用 http://localhost/prod-api/news 就会被转发到 https://http://gmall-h5-api.atguigu.cn/news 来获取 news 接口数据。

    • 部署演示地址:https://demo.gshopfront.dreamlove.top/
  • 官方的配置说明

    • https://docs.netlify.com/configure-builds/file-based-configuration/#headers
    • https://docs.netlify.com/routing/redirects/redirect-options/
    • https://docs.netlify.com/routing/redirects/#syntax-for-the-netlify-configuration-file

参考文章

猜你喜欢

转载自blog.csdn.net/u014582342/article/details/129367855