search
HomeWeb Front-endJS TutorialCross-domain issues with proxyTable in vue-cli project

What is cross-domain?

The same-origin policy stipulates that if any of the protocols, domain names, and ports of two URLs are different, they are considered to be cross-origin. This article mainly introduces to you a summary of the proxyTable cross-domain issues in the vue-cli project. The editor thinks it is quite good, so I will share it with you now and give you a reference. Let’s follow the editor to take a look, I hope it can help everyone.

What are the cross-domain solutions?

1.JSONP is the abbreviation of JSON with padding (filled JSON or parameterized JSON).

The principle of JSONP to implement cross-domain requests is simply to dynamically create the <script> tag, and then use the src of <script> to obtain cross-domain data without being subject to the same-origin policy. </script>

JSONP consists of two parts: callback function and data. The callback function is the function that should be called in the page when the response comes. The name of the callback function is usually specified in the request. The data is the JSON data passed into the callback function.
Dynamicly create the <script> tag, set its src, and set the callback function in src: </script>

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);

In the page, the returned JSON is passed into the callback function as a parameter, and we use the callback function to Operation data.

function handleResponse(response){
  // 对response数据进行操作代码
  console.log(response)
}

JSONP is still a popular cross-domain method. Although JSONP is convenient to use, there are also some problems:

First of all, JSONP loads code from other domains for execution. If the other domain is not secure, there is a good chance that some malicious code will be smuggled into the response, and there will be no way to pursue it other than to abandon the JSONP call entirely. Therefore, when using a web service that is not operated and maintained by yourself, you must ensure that it is safe and reliable.

JSONP has the advantage of directly accessing the response text, but it is not easy to confirm whether the JSONP request failed because the onerror event of the script tag has not been widely supported by browsers. In addition, it can only support GET method call.

2.cros cross-domain

The entire CORS communication process is automatically completed by the browser and does not require user participation. For developers, there is no difference between CORS communication and AJAX communication from the same source, and the code is exactly the same. Once the browser discovers that the AJAX request is cross-origin, it will automatically add some additional header information, and sometimes an additional request will be made, but the user will not feel it.

Therefore, the key to achieving CORS communication is the server. As long as the server implements the CORS interface, cross-origin communication is possible.

A commonly used complete cross-domain header:

let express=require("express");
let app=express();
app.use(function(req,res,next){
 //如果在webpack里配置了代理,那么这些响应头都不要了
 //只允许8080访问
  res.header('Access-Control-Allow-Origin','http://localhost:8080');

 //服务允许客户端发的方法
 res.header('Access-Control-Allow-Methods','GET,POST,DELETE,PUT');
 //服务器允许的请求头
 res.header('Access-Control-Allow-Headers','Content-Type,Accept');
 //跨域携带cookie 允许客户端把cookie发过来
 res.header('Access-Control-Allow-Credentials','true');
 //如果请求的方法是OPTIONS,那么意味着客户端只要响应头,直接结束响应即可
 if(req.method == 'OPTIONS'){
  res.end();
 }else{
  next();
 }
});
app.listen(3000);

3.hash + iframe

4.postMessage

5.WebSockets

The background only gives me the interface and cannot modify the background. How can I cross domains?

In actual work, the front-end and back-end cooperation is not so tacit. If the backend only gives me the interface and cannot modify the backend, how can I cross domains?
In the config files in the vue project and the react project, there is a proxy setting, which is used for cross-domain in the development environment. Setting it up will enable cross-domain.

The project built through vue-cli scaffolding can be achieved by modifying the proxyTable in index.js in the config folder:

module.exports = {
 dev: {
  env: {
   NODE_ENV: '"development"'
  },
  //proxy

  // 只能在开发环境中进行跨域,上线了要进行反向代理nginx设置
   proxyTable: {
    //这里理解成用‘/api'代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add'即可
   '/api': {
     target: 'http://news.baidu.com',//你要跨域的网址 比如 'http://news.baidu.com',
    secure: true, // 如果是https接口,需要配置这个参数
    changeOrigin: true,//这个参数是用来回避跨站问题的,配置完之后发请求时会自动修改http header里面的host,但是不会修改别的
    pathRewrite: {
     '^/api': '/api'//路径的替换规则
     //这里的配置是正则表达式,以/api开头的将会被用用‘/api'替换掉,假如后台文档的接口是 /api/list/xxx
     //前端api接口写:axios.get('/api/list/xxx') , 被处理之后实际访问的是:http://news.baidu.com/api/list/xxx
    }
   }
  },

Let us Use local services to test how to do cross-domain demo

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

1. Modify the index.js proxyTable:{} code in the config file and replace it with:

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

2. Write a backend yourself, use express+node.js, and do not set any cross-domain headers , the code is as follows:

Note that you need to prepare a list.json file in the current folder in advance 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));

//read
function read(cb) { //用来读取数据的,注意自己在mock文件夹下准备一些数据
 fs.readFile('./list.json','utf8',function (err,data) {
  if(err || data.length === 0){
   cb([]); // 如果有错误 或者文件没长度 就是空数组
  }else{
   cb(JSON.parse(data)); // 将读出来的内容转化成对象
  }
 })
}
//write
function write(data,cb) { // 写入内容
 fs.writeFile('./list.json',JSON.stringify(data),cb)
}
// 注意 没有设置跨域头
app.get('/api/list',function (req,res) {
 res.json(list);
});
app.listen(8000,()=>{
 console.log('8000 is ok');
});

3. API code called by the front end:

import axios from 'axios';
 axios.interceptors.response.use((res)=>{
 return res.data; // 在这里统一拦截结果 把结果处理成res.data
});
export function getLists() {
  return axios.get('/api/list');
}

4. Call the interface cross-domain in the component and print the data

Introduce the api in 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,"我请求的数据");
  },

5. View the console , print out the data, there is no error guarantee, it means the cross-domain is successful, the proxy service is successful


The development environment is successfully cross-domain , what should I do if I go online?

When going online, you need to set up nginx reverse proxy and distinguish environment variables. Please see the picture for specific settings:

Related recommendations:

About vue2.0 setting proxyTable to use axios for cross-domain requests

The above is the detailed content of Cross-domain issues with proxyTable in vue-cli project. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment