前言
在学习Vite+ Axios进行前后端分离时,出现了跨域问题,研究Vite文档后,解决了该问题
提示:以下是本篇文章正文内容,下面案例可供参考
一、遇到的问题
二、分析及解决方式
1.分析
跨域主要是同源策略原因导致;
什么是同源:
即——同协议,同ip,同端口;
所以跨域问题,是请求与返回不同源导致;
2.解决跨域问题
为了解决该问题,我去翻了翻vite的官方文档:https://vitejs.dev/config/server-options.html
export default defineConfig({ server: { proxy: { // string shorthand: http://localhost:5173/foo -> http://localhost:4567/foo '/foo': 'http://localhost:4567', // with options: http://localhost:5173/api/bar-> http://jsonplaceholder.typicode.com/bar '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, // with RegEx: http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/ '^/fallback/.*': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/fallback/, ''), }, // Using the proxy instance '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, configure: (proxy, options) => { // proxy will be an instance of 'http-proxy' }, }, // Proxying websockets or socket.io: ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io '/socket.io': { target: 'ws://localhost:5174', ws: true, }, }, }, })
里面有关于服务代理的配置解释,我们需要在vite.config.js中加入以上server.proxy配置;
'/api'就是针对api请求的拦截,名字可以自定义,主要是针对类似:/api/getInfo这类的拦截,将请求,全部拦截为api下的target,再经过rewrite path ,将请求路径进一步组装成需要的样子;
其中'changeOrigin',是关于host header的修改,true就是用target替换host header;false就是默认不替换,使用前端host,具体可以自行前后端验证;也就是说,这块和跨域暂时看来,没多大关系,可以不加;
rewrite:重写可以将路径改为你喜欢的样子;
基本上axios有用过,在vite.config.js这里再加上这个配置,报错就解决了,接口也可以正常调用了;
总结
vite + axios基础知识提升