Vite+Axios项目请求后端接口相关配置内容

一、相对地址请求

在实际项目中使用相对请求地址的情况比较多。

1. 封装请求文件

下面是封装Axios请求文件request.ts

ts 复制代码
import axios from 'axios'

const instance = axios.create({
  baseURL: '/pjone-server',
  timeout: 5000,
})
// 添加请求拦截器
instance.interceptors.request.use(config => {
  // todo:请求拦截逻辑代码
  return config
},
(error) => {
  return Promise.reject(new Error(error))
},
)
// 添加响应拦截器
instance.interceptors.response.use(response => {
  // todo:响应拦截逻辑
)

export default instance

2. 具体请求调用

javascript 复制代码
import request from './request'

export const getRecordsNum = () => {
  return request({
    url: '/lifeColor/getRecordsNum',
  })
}

3. 前端请求路径

通过上述配置,前端页面调用请求的路径为:

http://localhost:3000/pjone-server/lifeColor/getRecordsNum

4. 后端API接口

本地启动后端api为 http://localhost:1304/pjone-server/lifeColor/getRecordsNum 由于端口不同,这就导致跨域问题。这时就需要代理后端接口让前端能够调用到。

开发环境和生产环境的处理方式不同。

5. 开发环境代理

参考:入口vite.config.ts文件中配置以下内容

ts 复制代码
export default defineConfig({
  server: {
    proxy: {
      '/pjone-server': {
        target: 'http://127.0.0.1:1304/',
        changeOrigin: true,
      }
    },
  }, 
})

在开发环境中,Vite 使用 vite.config.js 中的 proxy 选项来配置代理,完成在开发服务器中的转发请求。

6. 生产环境代理

在 Vite 项目部署之后,proxy的配置内容不再起作用。这时就需要在部署项目的Nginx中进行设置。

nginx.conf配置内容如下:

conf 复制代码
location /pjone-server {
	proxy_pass   http://127.0.0.1:1304/pjone-server;
}

二、 绝对地址请求

在封装Axios请求的baseURL中也可以使用绝对请求路径,例如:

ts 复制代码
const instance = axios.create({
  baseURL: 'http://127.0.0.1:3007/api',
  timeout: 5000,
})

后端允许跨域

该后台是express项目,因为设置了允许跨域,所以直接路径访问是没问题的。

ini 复制代码
const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors());
相关推荐
Wang's Blog1 小时前
Vibe Coding一人即团队系列28: 前端、后端与数据库的概念解析
前端·数据库
Dovis(誓平步青云)1 小时前
模拟器横评:电脑上看小说、追短剧用什么模拟器?MuMu、雷电、腾讯手游助手实测
android·java·服务器·前端·javascript·电脑
踩蚂蚁1 小时前
把自定义唤醒词部署到 ESP32-S3:ONNX 转 INT8 TFLite 的完整链路
前端
前端繁华如梦1 小时前
用 Vite + Electron + React + Python 重造 3D 服装打版软件
前端
豆沙沙包?1 小时前
函数重载/类和对象(P14-P60)
前端·算法
三十而立洋1 小时前
彻底搞懂跨域:原理、CORS、解决方案与实战避坑
前端
计算机魔术师1 小时前
ASR转录总出错?Google新模型WER降到2.6%,还能自动帮你改口误
前端
xcs194051 小时前
新版 IDEA(尤其是 2024/2025/2026)越来越臃肿
前端·人工智能·intellij-idea
Patrick_Wilson1 小时前
iOS 第三方浏览器图片下载失败问题
前端·ios·浏览器