前言
在前端开发中,Http请求的url地址,我们可以通过两种方式来进行配置,以方便我们进行环境(开发或生产)的切换;
一、绝对路径
绝对路径:包括协议名称、主机地址、端口、名称等的完整请求路径。
let url = `http://113.140.12.194:18083/chd/api/authentication/org-tree/chdsd/new-tree`;
this.$http({
url: url,
method: "get",
}).then(({ data }) => {
});
我们可在代码中直接使用接口的绝对路径,则最后请求的地址,就是该绝对路径。

我们也可通过配置Ajax的baseURL,来使用绝对路径;
// 配置Ajax
const http = axios.create({
baseURL: 'http://113.140.12.194:18083'
})
// 调用接口
let url = `/chd/api/authentication/org-tree/chdsd/new-tree`;
this.$http({
url: url,
method: "get",
}).then(({ data }) => {
});
二、相对路径
相对路径:不需要协议名、主机地址、端口、web项目名称,只需要请求的路径。
1. 以根路径开头
let url = `/chd/api/authentication/org-tree/chdsd/new-tree`;
this.$http({
url: url,
method: "get",
}).then(({ data }) => {
});
以根路径开头(/
)的请求路径,表示该路径是基于服务器的根路径的,则请求地址为服务器路径+url
在本地开发的时候,一般
http://localhost:3000
是作为服务器路径的;所以这里请求的地址是http://localhost:3000/chd/api/authentication/org-tree/chdsd/new-tree

2.不以根路径开头
let url = `chd/api/authentication/org-tree/chdsd/new-tree`;
this.$http({
url: url,
method: "get",
}).then(({ data }) => {
});
不以根路径开头,表示该路径是基于当前html路径的,请求地址为页面地址+url
。
后记:
在开发阶段,我们都是在本地搭建服务,此时本地的服务器地址是http://localhost:3000
(可配置),接口请求的最后路径则是http://localhost:3000+...
;但是实际上,请求的最后路径应该是http://113.140.12.194:18083+...
,那么此时我们就需要使用代理,把地址从http://localhost:3000
代理到实际的请求地址上;
网友评论