Home  >  Article  >  Web Front-end  >  Cross-domain issues with proxyTable in vue-cli project

Cross-domain issues with proxyTable in vue-cli project

亚连
亚连Original
2018-06-06 14:47:011759browse

This article mainly introduces a detailed summary of proxyTable cross-domain issues in the vue-cli project. Now I share it with you and give it a reference.

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.

What are the cross-domain solutions?

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

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

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 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, set its src, and set the callback function 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);

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 fails because the onerror event of the script tag has not been widely supported by browsers. In addition, it can only support GET method calls. .

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 I 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 perform cross-domain demo

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

1. Modify index.js proxyTable:{} 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 for reading Get 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 successful It's 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:

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use readline module and util module in Node.js

How to implement undo in Immutable.js Redo function (detailed tutorial)

There are several values ​​of bind variables in vue and methods to prevent them from changing (detailed tutorial)

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