proxy api is not working in Vite + Vue 3 project when it's deployed to Vercel

Viewed 139

I have an issue with Vite+Vue3 project.

I used Vite proxy to fetch data via api and it's working well in local.

But 404 error is caused when it's deployed to Vercel.com.

Vite configuration is like this.

// vite.config.ts
server: {
  port: 4000,
  proxy: {
    // 选项写法
    '/api': {
      target: 'http://xxx.xxx.xxx.xxx:9998',
      changeOrigin: true,
      rewrite: path => path.replace(/^\/api/, '')
    }
  },
  hmr: {
    overlay: false
  },
  host: '0.0.0.0'
},

Error on Vercel

I used this template: https://github.com/kailong321200875/vue-element-plus-admin

It's deployed to http://his-lemon.vercel.app/

The error is the same as in both Vite 2 and Vite 3.

How can I fix this?

1 Answers

You need to specify URL rewrites on the server side. For Vercel, you can add a vercel.json file to the root of your project.

{
    "rewrites": [
        { "source": "/api/:path(.*)", "destination": "http://xxx.xxx.xxx.xxx:9998/:path" },
        { "source": "/(.*)", "destination": "/index.html" }
    ]
}

If you deploy to Netlify, you would instead provide an _redirects file in the public folder th at looks like the following

/api*  http://xxx.xxx.xxx.xxx:9998/:splat  200
/* /index.html 200
Related