Home > Web Front-end > Front-end Q&A > A brief analysis of the causes and solutions to Vue cross-domain problems

A brief analysis of the causes and solutions to Vue cross-domain problems

PHPz
Release: 2023-04-26 16:54:11
Original
6339 people have browsed it

With the development of front-end technology, Vue has become a JavaScript framework that many developers love very much, not only because of its ease of use, efficiency, and flexibility, but also because of its rich supporting ecosystem. However, at the same time, as the scale of front-end projects becomes larger and larger, the deployment problems of Vue projects have gradually emerged. The most common problem is cross-domain problems. This article will introduce the causes, solutions and related practices of Vue cross-domain problems.

1. Why are there Vue cross-domain problems?

The reason why there are cross-domain problems in the Vue project is because of the browser's same-origin policy, which means that the front end cannot directly initiate cross-domain requests. The same-origin policy is a basic security policy, but it will also cause certain troubles for Vue developers during deployment. Generally speaking, the browser will determine whether the request has the same origin by determining whether the protocol (http or https), domain name and port of the two URLs are the same.

A typical example of cross-domain problems in Vue projects is that when the front-end project requests the back-end API through AJAX, if the URL of the back-end API is not in the same domain as the URL of the current Vue project, cross-domain problems will occur. question.

2. How to solve Vue cross-domain problems?

Now that the problem has been clarified, let’s find a way to solve this problem. Below, we will introduce three common methods to solve cross-domain problems, which are also the three most widely used methods.

1. Set CORS on the server

We can solve cross-domain problems by setting CORS on the server. CORS, or cross-origin resource sharing, is a server-side solution to cross-domain problems. The server tells the browser which domain name requests are allowed by setting the Access-Control-Allow-Origin header in the HTTP response. When the browser finds that the requested domain name is within the allowed access range, it can successfully return the request result.

The specific implementation method is as follows:

Set the Access-Control-Allow-Origin attribute in the back-end response header to allow front-end access:

Access-Control-Allow-Origin: *
Copy after login

In the above code, * Indicates that all request sources are allowed.

2. Use the proxyTable attribute of webpack-dev-server

In Vue, we can configure proxyTable through webpack-dev-server to solve cross-domain problems during development. proxyTable can proxy the developer's local requests to the server, effectively solving cross-domain problems.

The configuration method of proxyTable is as follows:

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

In the above code, /api indicates the request that needs to be proxied, target indicates the back-end server address that needs to be proxied, changeOrigin: true indicates whether to change the request The source, pathRewrite is used to rewrite the request path.

3. Use JSONP to solve cross-domain problems

JSONP is a cross-domain solution. It dynamically adds a script tag to the web page and uses this script tag to access cross-domain problems. Interface, obtain the corresponding results, and the front end encapsulates the request results in a callback function and returns it to implement cross-domain requests. The implementation of JSONP is that the backend returns a piece of JavaScript code. This code will call a callback function defined by the frontend and pass the data as a parameter to the callback function. The frontend obtains the backend by listening to the parameters in the callback function. data.

The following is the implementation of JSONP:

Back-end code:

app.get('/jsonp', (req, res) => {
    const { data } = req.query;
    const callback = req.query.callback;
    const result = callback + '(' + JSON.stringify({ code: 0, data: data }) + ')';
    res.end(result);
});
Copy after login

Front-end code:

function jsonp(url, callback) {
    const script = document.createElement('script');
    script.src = `${url}?callback=${callback}`;
    document.body.append(script);
}

jsonp('http://localhost:3000/jsonp', function (res) {
    console.log(res);
});
Copy after login

3. Cross-domain practice

Practice 1: Use webpack-dev-server to set proxyTable to solve cross-domain problems

Let’s use the front-end Vue project to initiate a request to the back-end API as an example to describe how to solve the problem through the proxyTable attribute of webpack-dev-server. Cross-domain issues.

1. Install webpack-dev-server and http-proxy-middleware

Install webpack-dev-server and http-proxy-middleware in the project.

npm install --save-dev webpack-dev-server http-proxy-middleware
Copy after login

2.Introduce http-proxy-middleware in the webpack configuration file

const proxyMiddleware = require('http-proxy-middleware')
Copy after login

3.Use proxyTable in the webpack-dev-server configuration

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

In the above code , we configured a /api proxy to proxy the request to the local port 3000.

4. Use proxy request API

In the Vue project code, we only need to use /api as the URL prefix, so that the request can be successfully proxy to the local 3000 port.

axios.get('/api/users')
Copy after login

Practice 2: Use CORS to solve cross-domain problems from the backend

We can set up CORS on the backend to solve cross-domain problems. Here we take the express framework of node.js as an example to introduce.

1. Install express

Install express in the project.

npm install express
Copy after login

2. Set CORS in the server.js or app.js file

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    next();
});
Copy after login

The above code sets CORS, allowing requests from all sources to be returned successfully.

3. In the back-end API, add the previous CORS settings

app.get('/users', (req, res) => {
    const data = [
        { id: 1, name: 'Jack' },
        { id: 2, name: 'Lily' }
    ];
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.json(data);
});
Copy after login

In the above code, we add the Access-Control-Allow-Origin attribute in the server response header to use Tells the browser which domain names to allow requests for.

4. Initiate a request in the Vue project

For Ajax requests in the Vue project, we only need to initiate the request in the normal way.

axios.get('/users').then(resp => {
    console.log(resp.data);
});
Copy after login

Conclusion

Vue’s cross-domain problem is a relatively common problem, but it can be easily solved as long as you master the solution. For cross-domain issues, we can set up CORS on the server, use the proxyTable attribute of webpack-dev-server, or use JSONP to solve the problem. This article introduces the specific use of these three methods through practice, and hopes that readers will gain more in practice.

The above is the detailed content of A brief analysis of the causes and solutions to Vue cross-domain problems. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template