Detailed description of the proxyTable cross-domain problem summary in the vue-cli project, vue-cliproxytable

Source: Internet
Author: User
Tags nginx reverse proxy

Detailed description of the proxyTable cross-domain problem summary in the vue-cli project, vue-cliproxytable

What is cross-origin?

The same-origin policy specifies that the two URLs are considered cross-origin if there is any difference between the Protocol, domain name, and port.

What are the cross-origin solutions?

1. JSONP is short for JSON with padding (filling JSON or parameter JSON.

The principle of implementing cross-origin requests in JSONP is to dynamically create <script> tags, and then use the <script> src to obtain data across domains without the same-origin policy constraints.

JSONP consists of two parts:Callback functions and data. The callback function is the function that should be called on the page when the response arrives. The callback function name is generally specified in the request. The data is the JSON data in the callback function.
Dynamically create the <script> label and set its src. The callback function is set in src:

var script = document.createElement("script");script.src = "https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse";document.body.insertBefore(script, document.body.firstChild);

On the page, the returned JSON is passed into the callback function as a parameter. We use the callback function to operate the data.

Function handleResponse (response) {// operation code console. log (response) on response Data )}

JSONP is currently a popular cross-origin method. Although JSONP is easy to use, there are also some problems:

First, JSONP loads code execution from other domains. If other domains are not secure, some malicious code may be included in the response. In this case, there is no way to investigate the issue except for completely giving up the JSONP call. Therefore, when using a Web service that is not operated and maintained by yourself, you must ensure its security and reliability.

JSONP has the advantage of directly accessing the response text, but it is not easy to check whether JSONP fails the request because the onerror event of the script tag has not been widely supported by the browser, in addition, it can only be called in GET mode.

2. cros cross-Origin

The entire CORS communication process is completed automatically by the browser without the user's participation. For developers, CORS communication is no different from AJAX communication of the same source, and the code is exactly the same. Once the browser finds that AJAX requests are cross-origin, it will automatically add some additional header information, and sometimes there will be an additional request, but the user will not feel it.

Therefore, the key to CORS communication is the server. As long as the server implements the CORS interface, cross-source communication can be achieved.

A commonly used complete cross-origin header:

Let express = require ("express"); let app = express (); app. use (function (req, res, next) {// If a proxy is configured in webpack, these response headers are not allowed. // only 8080 access to res is allowed. header ('access-Control-Allow-origin', 'HTTP: // localhost: 100'); // method res that the service allows the client to send. header ('access-Control-Allow-Methods ', 'Get, POST, DELETE, put'); // The Request header res allowed by the server. header ('access-Control-Allow-headers', 'content-Type, Accept '); // Cross-Domain cookie carrying allows the client to send the cookie to res. header ('access-Control-Allow-credentials', 'true'); // if the request method is OPTIONS, the client only needs the response header, directly end the response. if (req. method = 'options') {res. end () ;}else {next () ;}}); app. listen (0, 3000 );

3. hash + iframe

4. postMessage

5. WebSockets

The backend only gives me the interface and cannot modify the backend. How can I cross-origin?

In actual work, the frontend and backend cooperation is not so tacit. If the backend only gives me interfaces and cannot modify the backend, how does one cross-origin?
In the config file of the vue project and react project, there is a proxy setting, which is used for cross-origin in the development environment. You can set it to implement cross-origin.

You can modify the proxyTable in index. js in the config folder for the project created through vue-cli scaffolding:

Module. exports = {dev: {env: {NODE_ENV: '"development"'}, // proxy // you can only perform cross-origin operations in the development environment, when going online, you need to set proxyTable in reverse proxy nginx: {// here it is interpreted as replacing the address in target with '/api, when we drop the interface in the following components, we directly use the api instead. For example, I want to call 'HTTP: // 40.00.100.100: 3002/user/add ', directly write '/api/user/add' to'/api': {target: 'http: // news.baidu.com '. // The URL you want to cross-origin, such as 'HTTP: // news.baidu.com ', secure: true, // if it is an https interface, you need to configure this parameter changeOrigin: true, // this parameter is used to avoid cross-site issues, after configuration, the host in the http header will be automatically modified when a request is sent, but other pathRewrite: {'^/api' will not be modified ': '/api' // path replacement rule // The configuration here is a regular expression. The rules starting with/api will be replaced with'/api, assume that the interface of the background document is/api/list/xxx // write the frontend api: axios. get ('/api/list/XXX'), actually accessed after being processed is: http://news.baidu.com/api/list/xxx }}},

Let's use a local service to test how to use a cross-origin demo.

0. Scaffolding built with vue-cli,npm run dev The frontend port number is generally:http://localhost:8080

1. Modify index. js in the config fileproxyTable:{}Replace the following code:

module.exports = { dev: {    proxyTable: {   '/api': {     target: 'http://localhost:8000',    secure: true,      changeOrigin: true,    pathRewrite: {     '^/api': '/api'    }   }  },

2. Write your own background and use express + node. js without setting any cross-origin headers. The Code is as follows:

Note that you need to prepare a list. json file in advance under the current folder to read data and return data. Fs. readFile ('./list. json', 'utf8', cb)

Let express = require ('express '); let app = express (); let fs = require ('fs'); let list = require ('. /list'); let bodyParser = require ('body-parser '); app. use (bodyParser. json (); app. use (express. static (_ dirname); // readfunction read (cb) {// used to read data. Note that you have prepared some data fs in the mock folder. readFile ('. /list. json', 'utf8', function (err, data) {if (err | data. length = 0) {cb ([]); // if an error occurs or the file length is not an empty array} else {cb (JSON. parse (data); // convert the read content to an object})} // writefunction write (data, cb) {// write content fs. writeFile ('. /list. json ', JSON. stringify (data), cb)} // note that the cross-origin header app is not set. get ('/api/list', function (req, res) {res. json (list) ;}); app. listen (8000, () => {console. log ('2014 is OK ');});

3. the api code obtained by the front-end:

Import axios from 'axios '; axios. interceptors. response. use (res) => {return res. data; // here, the uniform interception result is processed as res. data}); export function getLists () {return axios. get ('/api/list ');}

4. Cross-origin Retrieval Interface in the component to print data

Introduce an api to a file to test the data returned by the printed interface.

Import {getLists} from '.. /.. /api/index'export default {async created () {let dataList = await getLists (); console. log (dataList, "My requested data ");},

5. Check the console and print out the data. If no error is saved, the cross-domain operation is successful and the proxy service is successful.


The development environment has been successfully cross-origin. What should I do if I go online?

Nginx reverse proxy settings are required for the launch, and environment variables should be differentiated. For specific settings, see the image:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.