About vue solving cross-domain routing conflicts
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' } },
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' }, },
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':'/' } }, },
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); }) }
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'
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/' }
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
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); }) }
Final code
Configure in the agent
proxyTable: { '/api/**': { target: 'http://localhost:3000', pathRewrite:{ '^/api':'/' } }, },
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/' }
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')
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
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); }) }
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 }
Set the target to the domain name we need to access.
3. Then set the global properties in main.js:
Vue.prototype.HOST = '/api'
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('调用失败'); });
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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.

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

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 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 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"

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
