Home Web Front-end JS Tutorial About vue solving cross-domain routing conflicts

About vue solving cross-domain routing conflicts

Dec 28, 2017 am 10:35 AM
conflict routing question

Vue.js (pronounced /vjuː/, similar to view) is a progressive framework for building user interfaces. This article gives you a detailed introduction to the analysis of Vue's ideas for solving cross-domain routing conflicts. Friends who need it can refer to it. I hope it can help everyone.

vue Introduction

Vue.js (pronounced /vjuː/, similar to view) is a progressive framework for building user interfaces.

Vue only focuses on the view layer and adopts a bottom-up incremental development design.

The goal of Vue is to implement responsive data binding and composed view components through the simplest possible API.

Vue is very easy to learn. This tutorial is based on Vue 2.1.8 version test.

When we configure the following proxy in the routing, we can solve the cross-domain problem

proxyTable: {
   '/goods/*': {
    target: 'http://localhost:3000'
   },
   '/users/*': {
    target: 'http://localhost:3000'
   }
  },
Copy after login

This configuration method solves the cross-domain problem to a certain extent, but it will bring some problems ,

For example, our vue route is also named goods, and conflicts will occur at this time.

If there are many interfaces in the project, it will be very troublesome to configure them all here, and it is easy to generate routes. conflict.

Correct posture

If all interfaces are unified and standardized as one entrance, the conflict will be resolved to a certain extent

Unify the above configuration and add /api/ in front of it

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000'
   },
  },
Copy after login

If we configure it in this way, it will change when using http requests. An api will be added in front of the request. The relative route will also change, and api will be added in front of the interface. , this will also be very troublesome. We can use the following methods to solve this problem

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000',
    pathRewrite:{
     '^/api':'/'
    }
   },
  },
Copy after login
Copy after login

The above code is to remove our virtual api interface. At this time, when we actually go to the backend to request, it will not After adding the api prefix, when we make a front-end http request, we must also add the api prefix to match the proxy. The code is as follows:

logout(){
  axios.post('/api/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  axios.post('/api/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }
Copy after login

We can use the baseUrl of axios to directly default to api. In this way, every time we visit, the api prefix will be automatically added, and we do not need to manually write this prefix on each interface.

The configuration in the entry file is as follows:

import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = 'api'
Copy after login

If this configuration 'api/' will read the local domain by default

If configured like this, the production and development environments will not be distinguished

Create a new api.config.js in the config folder The configuration file

const isPro = Object.is(process.env.NODE_ENV, 'production')
module.exports = {
 baseUrl: isPro ? 'http://www.vnshop.cn/api/' : 'api/'
}
Copy after login
Copy after login

is then introduced in main.js, which ensures dynamic matching of the production and development definition prefix

import apiConfig from '../config/api.config'
import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = apiConfig.baseUrl
Copy after login
Copy after login

After the above configuration, it can be easily accessed in the dom. There is no need to introduce the axios module into any component.

logout(){
  this.$http.post('/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  this.$http.post('/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }
Copy after login
Copy after login

Final code

Configure in the agent

proxyTable: {
   '/api/**': {
    target: 'http://localhost:3000',
    pathRewrite:{
     '^/api':'/'
    }
   },
  },
Copy after login
Copy after login

Configure api.config.js in config

Create a new api in the config folder .config.js configuration file

const isPro = Object.is(process.env.NODE_ENV, 'production')
module.exports = {
 baseUrl: isPro ? 'http://www.vnshop.cn/api/' : 'api/'
}
Copy after login
Copy after login

I don’t know much about production and development configuration

You can go to dev-server.js to see the configuration code

const webpackConfig = (process.env.NODE_ENV === 'testing' || process.env.NODE_ENV === 'production') ?
 require('./webpack.prod.conf') :
 require('./webpack.dev.conf')
Copy after login

In the main.js entrance Configuration in the file

import apiConfig from '../config/api.config'
import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)
Axios.defaults.baseURL = apiConfig.baseUrl
Copy after login
Copy after login

How to request api in dom

logout(){
  this.$http.post('/users/logout').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 },
 getGoods(){
  this.$http.post('/goods/list').then(result=>{
   let res = result.data;
   this.nickName = '';
   console.log(res);
  })
 }
Copy after login
Copy after login

PS: Let’s learn the cross-domain settings under vue through a piece of code

1. Developed using vue Cross-domain issues are often involved. In fact, in vue cli, there are files for us to set up cross-domain requests.

2. When cross-domain requests cannot be made, we can modify the dev:{} part in index.js in the config folder under the project.

dev: {
  env: require('./dev.env'),
  port: 8080,
  autoOpenBrowser: false,
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  proxyTable: {
    '/api': {
      target: 'http://api.douban.com/v2',
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    }
  },
  // CSS Sourcemaps off by default because relative paths are "buggy"
  // with this option, according to the CSS-Loader README
  // (https://github.com/webpack/css-loader#sourcemaps)
  // In our experience, they generally work as expected,
  // just be aware of this issue when enabling this option.
  cssSourceMap: false
}
Copy after login

Set the target to the domain name we need to access.

3. Then set the global properties in main.js:

Vue.prototype.HOST = '/api'
Copy after login

4. At this point, we can use this domain name globally, as follows:

var url = this.HOST + '/movie/in_theaters'
  this.$http.get(url).then(res => {
   this.movieList = res.data.subjects;
  },res => {
   console.info('调用失败');
  });
Copy after login

Related recommendations :

Detailed example of the principle of Ajax cross-domain request

Solution to the problem of 2 requests when ajax cross-domain submission in jquery

How to understand Js cross-domain

The above is the detailed content of About vue solving cross-domain routing conflicts. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Apache Camel: Building a flexible and efficient service-oriented architecture Java Apache Camel: Building a flexible and efficient service-oriented architecture Feb 19, 2024 pm 04:12 PM

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

Teach you how to diagnose common iPhone problems Teach you how to diagnose common iPhone problems Dec 03, 2023 am 08:15 AM

Known for its powerful performance and versatile features, the iPhone is not immune to the occasional hiccup or technical difficulty, a common trait among complex electronic devices. Experiencing iPhone problems can be frustrating, but usually no alarm is needed. In this comprehensive guide, we aim to demystify some of the most commonly encountered challenges associated with iPhone usage. Our step-by-step approach is designed to help you resolve these common issues, providing practical solutions and troubleshooting tips to get your equipment back in peak working order. Whether you're facing a glitch or a more complex problem, this article can help you resolve them effectively. General Troubleshooting Tips Before delving into specific troubleshooting steps, here are some helpful

Guide to uninstalling the NumPy library to avoid conflicts and errors Guide to uninstalling the NumPy library to avoid conflicts and errors Jan 26, 2024 am 10:22 AM

The NumPy library is one of the important libraries in Python for scientific computing and data analysis. However, sometimes we may need to uninstall the NumPy library, perhaps because we need to upgrade the version or resolve conflicts with other libraries. This article will introduce readers to how to correctly uninstall the NumPy library to avoid possible conflicts and errors, and demonstrate the operation process through specific code examples. Before we start uninstalling the NumPy library, we need to make sure that the pip tool is installed, because pip is the package management tool for Python.

How to solve the problem that jQuery cannot obtain the form element value How to solve the problem that jQuery cannot obtain the form element value Feb 19, 2024 pm 02:01 PM

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

Use JavaScript functions to implement web page navigation and routing Use JavaScript functions to implement web page navigation and routing Nov 04, 2023 am 09:46 AM

In modern web applications, implementing web page navigation and routing is a very important part. Using JavaScript functions to implement this function can make our web applications more flexible, scalable and user-friendly. This article will introduce how to use JavaScript functions to implement web page navigation and routing, and provide specific code examples. Implementing web page navigation For a web application, web page navigation is the most frequently operated part by users. When a user clicks on the page

Implementation method and experience summary of flexibly configuring routing rules in PHP Implementation method and experience summary of flexibly configuring routing rules in PHP Oct 15, 2023 pm 03:43 PM

Implementation method and experience summary of flexible configuration of routing rules in PHP Introduction: In Web development, routing rules are a very important part, which determines the corresponding relationship between URL and specific PHP scripts. In the traditional development method, we usually configure various URL rules in the routing file, and then map the URL to the corresponding script path. However, as the complexity of the project increases and business requirements change, it will become very cumbersome and inflexible if each URL needs to be configured manually. So, how to implement in PHP

What are the questions in the Rulong 8 Wine Master exam? What are the questions in the Rulong 8 Wine Master exam? Feb 02, 2024 am 10:18 AM

What are the questions involved in the Yulong 8 Wine Master exam? What is the corresponding answer? How to pass the exam quickly? There are many questions that need to be answered in the Master of Wine Examination activities, and we can refer to the answers to solve them. These questions all involve knowledge of wine. If you need a reference, let’s take a look at the detailed analysis of the answers to the Yakuza 8 Wine Master exam questions! Detailed explanation of answers to questions in the Rulong 8 Wine Master exam 1. Questions about "wine". This is a distilled liquor produced by a distillery established by the royal family. It is brewed from the sugar of sugarcane grown in large quantities in Hawaii. What is the name of this wine? Answer: Rum 2. Question about "wine". The picture shows a drink made from dry ginseng and dry vermouth. It is characterized by the addition of olives and is known as "cockney"

How to solve the problem of the start menu that cannot be used after win11 installation How to solve the problem of the start menu that cannot be used after win11 installation Jan 06, 2024 pm 05:14 PM

Many users have tried to update the win11 system, but found that the start menu cannot be used after the update. This may be because there is a problem with the latest update. We can wait for Microsoft to fix or uninstall these updates to solve the problem. Let's take a look at it together. Solution. What to do if the start menu cannot be used after win11 is installed. Method 1: 1. First open the control panel in win11. 2. Then click the "Uninstall a program" button below the program. 3. Enter the uninstall interface and find "View installed updates" in the upper left corner. 4. After entering, you can view the update time in the update information and uninstall all recent updates. Method 2: 1. In addition, we can also directly download the win11 system without updates. 2. This is a product without the most

See all articles