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());
相关推荐
恋猫de小郭5 小时前
AGENTS.md 真的对 AI Coding 有用吗?或许在此之前你没用对?
前端·人工智能·ai编程
sunny_7 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
前端·rust·前端工程化
rfidunion8 小时前
springboot+VUE+部署(12。Nginx和前端配置遇到的问题)
前端·vue.js·spring boot
珹洺8 小时前
Java-servlet(五)手把手教你利用Servlet配置HTML请求与相应
java·运维·服务器·前端·servlet·html·maven
QQ24391978 小时前
语言在线考试与学习交流网页平台信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·spring boot·sql·学习·java-ee
范特西.i9 小时前
QT聊天项目(6)
前端
a1117769 小时前
水体渲染系统(html开源)
前端·开源·threejs·水体渲染
程序员小李白9 小时前
CSS 盒子模型
前端·css·html
Zzz不能停9 小时前
单行 / 多行文本显示省略号(CSS 实现)
前端·css
xiaoxue..9 小时前
TailwindCSS:从“样式民工”到“UI乐高大师”的逆袭
前端·css·ui