Cross-domain -Vue-Cli Configure proxy forwarding

The target

Resolve cross-domain problems in the development environment by configuring vuE-CLI request proxy

Vue-a cross-domain solution integrated in cli

There are two steps:

  1. Configure devServer in vue.config.js
  2. Ensure that the base address points to the local service

Vue-cli Resolve cross-domain configuration description

In the vue.config.js configuration file, there is an item called devServer, which is the main character of the next operation.

module.exports = {
  devServer: {
    // Proxy configuration
    proxy: {
    // 'http://localhost:3000' // interface server
      '/api': {
        / / / API/users request will request broker to http://localhost:3000/api/users
        target: 'http://localhost:3000' 
        // If you don't want to pass/API, you need to rewrite the path
        pathRewrite: { '^/api': ' '},}}}}Copy the code

Ensure that the base address points to the local service

.env.development

// Base address in the development environment
VUE_APP_BASE_API = '/api'
Copy the code
  • api/user.js
export function login(formData) {
  return request({
// url: 'api/sys/login',
+   url: '/sys/login'.// The previous API is omitted
    method: 'POST'.data: formData
  })
}
Copy the code

Note:

  1. Vue-cli integrates the cross-domain proxy function —— can only be used during development.
  2. In the vue.config.js file, you can configure proxy in the specified format under devServe, and then restart the project.
  3. The ajax base address, baseUrl, must be a relative address, not an absolute one