---
# System prepended metadata

title: Vue API Request設計
tags: [Vue2, Vue-cli]

---

# Vue API Request設計
###### tags: `Vue-cli`、`Vue2`
### 1.src>api>request.js
#### 透過axios建立基礎連線，並設定timeout時間；下方interceptors為攔劫器
```javascript=
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 60000
})

service.interceptors.request.use(
  config => {
  //資料送出前，可針對每個送出做最後處理
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
  //回傳結果
  },
  error=>{
  //錯誤處理
  }
)
export default service
```
### 2.src>api>index.js
#### 建立基本傳輸格式，並在此設定header
```javascript=
const request = ({ name = "", url = "", options = {}, otherOption = {}, method = "post" }) => {
  const baseRequest = {
    url: url + urlParam,
    method,
    headers: {
      "Content-Type": "application/json",
      "If-Modified-Since": "0"
    }
  }

  return new Promise(resolve => {
    axios(
      Object.assign(baseRequest, {
        [key]: options
      })
    )
      .then(response => {
        //回傳到前台統一格式
        resolve({
          status: !response.errorCode,
          errorCode: response.errorCode,
          data: response.data
        })
      })
      .catch(error => {
        resolve({
          status: false,
          error
        })
      })
  })
}
const requestFactory = requestConfig => options => {
  return request({
    options,
    ...requestConfig
  })
}

export default requestFactory
```
### 3.API範例
```javascript=
export const apiExample = requestFactory({
  name: "exampleName",
  url: `apiUrl`,
  method: "post"
})
```