天天看點

axios 及proxy 代理

aoxis 封裝請求

安裝依賴

npm install axios

全局的 axios 預設值

axios.defaults.baseURL = ‘https://api.example.com’;

axios.defaults.headers.common[‘Authorization’] = AUTH_TOKEN;

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

自定義執行個體預設值

// Set config defaults when creating the instance

const instance = axios.create({

baseURL: ‘/’,

timeout: 5000

});

攔截器

在請求或響應被 then 或 catch 處理前攔截它們。

// 添加請求攔截器

axios.interceptors.request.use(function (config) {

// 在發送請求之前做些什麼

return config;

}, function (error) {

// 對請求錯誤做些什麼

return Promise.reject(error);

});

// 添加響應攔截器

axios.interceptors.response.use(function (response) {

// 對響應資料做點什麼

return response;

}, function (error) {

// 對響應錯誤做點什麼

return Promise.reject(error);

});

配置代理,可以通路到背景的伺服器位址

安裝依賴

npm install --save-dev http-proxy-middleware

在src檔案夾中建立setupProxy.js内容配置如下

const {createProxyMiddleware} = require(‘http-proxy-middleware’);

module.exports = function(app) {

//可以配置多個 不同的url

app.use(’/api’, createProxyMiddleware({

target: ‘’,//背景伺服器位址

changeOrigin: true,

pathRewrite: {

‘^/api’: ‘’,

},

})

)

app.use(’/api’, createProxyMiddleware({

target: ‘’,//背景伺服器位址

changeOrigin: true,

pathRewrite: {

‘^/api’: ‘’,

},

})

)

}

繼續閱讀