最近在写前端的时候想调用一下本地的后端接口,接口地址是8889。所以在前端配置了跨域请求,记录一下。
首先在vite.cofig.ts中配置,完整代码:
注意:要把localhost换成127.0.0.1
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
// 使用 proxy 实例
'/api': {
target: 'http://127.0.0.1:8889',//注意这里不能用http://localhost:8889
changeOrigin: true,
rewrite: (path) => path.replace('/api','')
},
}
}
})
然后我们调用接口的时候如下:
import axios from "axios";
const userName = ref("");
const passWord = ref("");
const api_login = async (username: String, password: String) => {
try {
const response = await axios.post(`/api/user/login`, {
userName: username,
passWord: password,
});
if (response.data.success) {
console.log("Login successful");
router.push("/home");
} else {
console.log("Login failed");
}
} catch (error) {
console.error("Error logging in:", error.message);
}
};
测试,可以看到成功调通了: