美文网首页
在Vue3中使用vite配置proxy实现跨域请求

在Vue3中使用vite配置proxy实现跨域请求

作者: boldiy | 来源:发表于2024-04-07 13:43 被阅读0次

在项目根目录中找到vite.config.ts文件,配置以下代理:

export default defineConfig({
  server: {
    proxy: {
      '/page': {
        target: 'http://www.baidu.com/api/', // 目标服务器地址
        changeOrigin: true, // 启用代理时,改变源地址
        headers: {
          "Authorization": "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAi"  //设置请求报头
        }
      }
    }
  },
})

调用方法:

axios.post('http://localhost:5173/page', {
  headers: {
    "Content-Type": "application/json",
  }
})
  .then((data: any) => {
    console.log(data);
  })

相当于请求了后端服务接口:http://www.baidu.com/api/page

相关文章

网友评论

      本文标题:在Vue3中使用vite配置proxy实现跨域请求

      本文链接:https://www.haomeiwen.com/subject/hxttxjtx.html