在发出请求之前,可以做一些配置信息,这样可以带来一些额外的好处。

1、设置超时时间:请求发出去之后,如果隔了多少时间后台没有响应,前端认为已经出错了,超时了。

2、baseURL:向后台发请求的时候我们可以提前设置一下后台基准的请求地址,这样后面再发请求的时候,只需要写后面的路径就可以了。

// 创建axios实例
const service = axios.create({
  // baseURL: 'http://localhost:8008/api',
  baseURL: '/api',
  timeout: 5000000
})

如果baseURL值为http://localhost:8008/api,那么就会拼接js中的路径,如果是/area/findAreasByPCity,则会访问http://localhost:8008/api/area/findAreasByPCity。

如果baseURL值为/api,则在proxytable中代码如下:

proxyTable: {
      '/api': {
        target: `http://192.168.43.242:8008`,
        changeOrigin: true
      }
    },

如果是/area/findAreasByPCity,从而访问http://192.168.43.242:8008/api/area/findAreasByPCity。

3、设置请求头

 

4、配置axios请求头中的content-type为指定类型

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

 

posted on 2021-06-22 09:54  周文豪  阅读(6453)  评论(0编辑  收藏  举报