What is the point of proxy in my vue.config file?

Viewed 1097

I am a bit confused what the proxy '^/api' in my vue.config.js does. When I do an axios request from my frontend form , I know that it is handled in by my http-common.js and tutorial_data_services.js files.

I am trying to learn and understand this. Could anyone help advice?

vue.config.js

const path = require('path');

module.exports = {
    outputDir: path.resolve(__dirname, '../server/public'),
    devServer:{
        proxy:{
            '^/api': {
                target: 'http://localhost:8080',
                changeOrigin: true,
                secure:false,
                pathRewrite: {'^/api': '/api'},
                logLevel: 'debug' 
            }
        }
    }
}

http-common.js

import axios from 'axios'

export default axios.create({
  baseURL: 'http://localhost:8080/',
  headers: {
    'Content-type': 'application/json'
  }
})

tutorial_data_services.js

import http from '../http-common'

class TutorialDataService {
  getAll() {
    return http.get('/tutorials')
  }

  get(id) {
    return http.get(`/tutorials/${id}`)
  }

  create(data) {
    return http.post('/tutorials', data)
  }

}

export default new TutorialDataService()
1 Answers

The devServer proxy checks each path prior to routing and redirects any matches. The rule in your example is proxying any requests to the /api path, including any string that comes after it. So assuming your Vue CLI devServer is running at port 8080, this rule will match any requests you send to URLs like :

None of the requests you've shown above are sent to an /api path, so this rule is never being triggered by your app currently. If it was, the target property specifies the path to redirect to, and the devServer also appends the matched portion to the end of the target path. So, the above examples would redirect to:

The target + the matched portion. In this case: no redirect whatsoever (and actually causes a redirect loop).

You could send the requests to another target path instead, and you can rewrite a portion of that path any way you like (or remove it) using pathRewrite. In your example, pathRewrite also does nothing, by rewriting the string '/api' as '/api'.

So there is no reason to use this proxy and you can remove it.

One use of proxying is to let you send requests to a relative URL like '/api' that works in both production and development. In production, when the app is running on a server that also hosts the API, that relative path actually exists and so the app just works. In development, where you have the Vue CLI devServer at 8080, and, for example, a Node server at 3000, the app still works, by redirecting those relative URL requests from devServer to Node.

This is nice because then you don't have to mess with axios baseURL or .env variables or absolute paths just to get your dev API requests working.

Related