解决vue3/vite调用百度翻译api跨域的问题--纯前端
·
1. 配置 Vite 代理
在 Vite 项目的根目录下,找到 vite.config.js 文件(如果没有该文件,请创建一个)。在该文件中配置代理服务器,以便将前端的请求转发到百度翻译 API。
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
//主要是这个
server: {
proxy: {
'/api': {
target: 'https://fanyi-api.baidu.com', // 百度翻译 API 的域名
changeOrigin: true, // 是否改变源地址
rewrite: (path) => path.replace(/^\/api/, '') // 重写路径
}
}
}
//--------------------------------
});
2. 修改前端请求地址
在前端代码中,将请求百度翻译 API 的地址改为代理服务器的地址。例如:
// 假设你使用的是 axios 进行 HTTP 请求
import axios from 'axios';
async function translateText(text) {
try {
const response = await axios.get('/api/api/trans/vip/translate', {
params: {
q: text,
from: 'auto',
to: 'en',
appid: 'YOUR_APPID',
salt: 'YOUR_SALT',
sign: 'YOUR_SIGN'
}
});
console.log(response.data);
} catch (error) {
console.error('翻译请求失败', error);
}
}
3. 启动 Vite 开发服务器
确保 Vite 开发服务器已启动,然后在前端应用中调用 translateText 函数进行翻译请求。
npm run dev
解释
- 代理配置:在
vite.config.js中,/api是前端请求的前缀,所有以/api开头的请求都会被代理到https://fanyi-api.baidu.com。 - 路径重写:
rewrite函数将请求路径中的/api前缀去掉,以便正确转发到目标 API。 - 前端请求:在前端代码中,将请求地址改为以
/api开头,这样 Vite 会自动将其代理到百度翻译 API。
通过这种方式,可以有效解决纯前端应用调用百度翻译 API 时的跨域问题。
更多推荐




所有评论(0)