Detailed explanation and usage of vue configuration api proxy

In the created vue framework, dev.env.js in the automatically generated config directory

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')ule.exports = merge(prodEnv, {
    
    
  NODE_ENV: '"development"',
  BASE_URL:'"/api"' //这里是自己修改的
})

index.js in the config directory (only key code)

  dev: {
    
    
    env:require('./dev.env'),//开发环境下
    // Paths
    assetsSubDirectory: 'static', //除index.html之外的静态资源要存放的路径
    assetsPublicPath: '/',//打包后,index.html里面引用资源的相对地址
    proxyTable: {
    
    
      //在api方式中,这里的对象名和dev.env.js的BASE_URL的值一样,可将BASE_URL的值替换
      '/api':{
    
    //在代理方式中,设置访问前缀为api,如果不管用,改成'/api/*'
        target:'http://11.0.34.122:5000',//本地测试
        changeOrigin:true,//在vue-cli3下默认为true,是否跨域请求
        //secure:true,//如果开头是https,打开这一条
        pathRewrite:{
    
    //配置跨域请求 ,如果后台的接口前缀不是api,则重写前缀名,比如'^/api':'/save',则配出来的接口是http://127.0.0.1:8080/save/login
        //   //'^api':'/api' 这种接口配出来是 http://127.0.0.1:8080/api/login(举例)
       '^/api':'' //则接口配出来是 http://127.0.0.1:8080/login(举例)
        // }
      }
    },...

Create a new folder api under src -> new index.js

import axios from 'axios'
const api = axios.create({
    
    
    baseURL:process.env.BASE_URL,
    timeout:2000000//请求超时
})
// 基础信息接口
export function getDefaultMess(dev){
    
     
    return api({
    
    
        url:'/basicInfo/BasicInfoGET',
        method:'get',
        params:{
    
    dev}
    })
}

Component call interface, referenced in vue file

import {
    
    getDefaultMess} from '../api/index'
export default {
    
    
	data(){
    
    return {
    
    a:'',b:''}},
	mounted:{
    
    this.loadPageMess()}, //初始化加载信息
	methods:{
    
    
		loadPageMess(){
    
    
			let _this = this
			getDefaultMess().then(res => {
    
    
				_this.a = res.data.a //举例,具体赋值看后台数据放在那里
				_this.b = res.data.b
			})
		}
	}
}

Note:
1. Never write comments in dev.env.js and prod.env.js under config, it will report an error.
2. Send data to the background. Use params when the method is get, for example, params:{dev}, pass to The backend is {dev:xxx}. When the method is post, either params or data can be used (attached: data is to directly transfer data, usually in json format, such as "{"a":123,"b":"hello"} ")
3. Introduce the api interface function, you do not need to add the prefix .this when calling, but the this point will be changed in the interface. When operating the variable or method in the component data(){return}, you need to pass et _this = this Then _this. component variable or method

Guess you like

Origin blog.csdn.net/weixin_43939111/article/details/110916103