Vite不会重写Axios实例 / VUE 3组成API的代理路径
我正在使用Coption API和Vite进行我的第一个项目。 我正在努力避免CORS问题,需要代表我的请求。
vite.config.js
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
server: {
proxy: {
'/api': {
target: 'https://dest.com/api',
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});
我正在使用vue-axios作为我的请求。
main.js
// Axios
import axios from 'axios';
import VueAxios from 'vue-axios';
import App from './App.vue';
import router from './router';
const app = createApp(App);
// Init
app.use(createPinia());
app.use(router);
app.use(PrimeVue);
app.use(VueAxios, axios);
app.mount('#app');
到目前为止,这很好。但是,当我从这样的自定义AXIOS实例中提出请求时,
import axios from 'axios';
export const SMCCLIENT = axios.create({
baseURL: `https://dest.com`,
auth: {
username: '',
password: '',
},
header: {
'Access-Control-Allow-Origin': '*',
},
});
代理不会处理请求。
test.vue
async function getElements() {
const test = await SMCCLIENT.get('/api/test/', {
});
console.log(test);
}
导致CORS错误
test.vue
async function getElements() {
const test = await axios.get('/api/test/', {
});
console.log(test);
}
工作效果很好 有什么想法吗?
I`m working on my first project with the composition api and vite.
I am trying to avoid a CORS problem and need to proxy my requests.
vite.config.js
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
server: {
proxy: {
'/api': {
target: 'https://dest.com/api',
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});
I am using vue-axios for my requests.
main.js
// Axios
import axios from 'axios';
import VueAxios from 'vue-axios';
import App from './App.vue';
import router from './router';
const app = createApp(App);
// Init
app.use(createPinia());
app.use(router);
app.use(PrimeVue);
app.use(VueAxios, axios);
app.mount('#app');
This is working fine so far. But when I make requests from a custom axios instance like this one
import axios from 'axios';
export const SMCCLIENT = axios.create({
baseURL: `https://dest.com`,
auth: {
username: '',
password: '',
},
header: {
'Access-Control-Allow-Origin': '*',
},
});
The proxy does not handle the requests.
Test.vue
async function getElements() {
const test = await SMCCLIENT.get('/api/test/', {
});
console.log(test);
}
Results in CORS Error
Test.vue
async function getElements() {
const test = await axios.get('/api/test/', {
});
console.log(test);
}
Works fine
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论