1. ホーム
  2. vue.js

Vueプロジェクトのビルド共通設定ファイル、request.jsとvue.config.js

2022-02-22 07:01:34
<パス

request.jsは、データを要求するために使用され、以下のコードでラップされています。

import axios from 'axios'

const request = axios.create({
	baseURL: '/api', // Note! Here is a global unified plus '/api' prefix, that is to say, all interfaces will add '/api' prefix in, when writing the interface inside the page do not add '/api', otherwise there will be two '/api', similar to '/api/api/user' such an error, remember!
    timeout: 5000
timeout: 5000 })

// request interceptor
// You can do some processing on the request since before it is sent
// such as tokenization and encryption of request parameters
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
  
 // config.headers['token'] = user.token; // set request headers
    return config
}, error => {
    return Promise.reject(error)
});

// response interceptor
// can unify the result after the interface response
request.interceptors.response.use(
    response => {
        let res = response.data;
        // If it is the returned file
        if (response.config.responseType === 'blob') {
            return res
        }
        // compatible with the string data returned by the server
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)


export default request



vue.config.js。

// Cross-domain configuration
module.exports = {
    devServer: { // Remember, don't write devServer wrong // Set local default port Optional
        port: 9876,
        proxy: { // set proxy, must be filled
            '/api': { //set interceptor interceptor format slash + interceptor name, name can be set by yourself
                target: 'http://localhost:9999', //proxy's target address
                changeOrigin: true, //whether to set the same origin, enter yes
                pathRewrite: { //path rewrite
                    '^/api': '' //Optionally ignore the contents of the interceptor
                }
            }
        }
    }
}