Front-end vue configuration reverse proxy proxy

Front-end vue configuration reverse proxy proxy devServer axios

*Analysis function During the development process, we will encounter request interface errors
Access to XMLHttpRequest at *** from originand require cross-domain error information

insert image description here

· 亿点小知识Several methods across domains

  1. The backend solves cross-domain problems through CORS
  2. The backend is reverse-proxyed through nginx
  3. The front end can implement cross-domain proxy through node middleware, the principle is roughly the same as nginx, and it realizes data forwarding by starting a proxy server.
  4. Reverse proxy of the front-end vue framework
  5. The above only exemplifies several common cross-domain methods. In fact, there are many ways to cross-domain, such as: document.domain + iframe cross-domain, postMessage, jsonp cross-domain, websocket, etc.

Here only the reverse proxy of the front-end vue framework is explained

  1. Check your axios configuration first
import axios from 'axios';
const instance = axios.create({
    
    
  baseURL:" http://10.0.0.7:8888/api", // 这里的api就对应了 proxy 配置的api
  timeout: 3000, // 请求响应的时间
  withCredentials: true,// axios 默认不会携带cookie
});
  1. Configure reverse proxy

Open the project vue.config.jsand configure devServer properties

devServer: {
    
    
    host: "0.0.0.0",// 允许外部ip访问
    port: 8080, // 自定义修改8080端口
    https: false,// 启用https
    open: false,//build自动打开浏览器
   proxy:{
    
    
            '/api':{
    
    // /api 是监听你请求的接口数据是否存在 /api 会把他替换成 target 的代理地址
                target: 'http://192.168.1.0:8000',//代理地址,这里设置的地址会代替axios中设置的baseURL
                changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
                //ws: true, // proxy websockets
                //pathRewrite方法重写url
                pathRewrite: {
    
    
                    '^/api': '/' 
                    //pathRewrite: {'^/api': '/'} 重写之后url为 http://192.168.1.0:80001/xxxx
                    //pathRewrite: {'^/api': '/api'} 重写之后url为 http://192.168.1.0:80001/api/xxxx
               }
        }}
  },
  1. Create a api.jsdedicated storage interface
import instance from './request'; //导入配置好的axios
// 请求登录接口 
export const login = (data) =>
  instance({
    
    
    url: '/login', //这些是具体的路径 不会被代理掉
    method: 'POST',
    data,
  });

The above is the reverse proxy performed by the front end through vue.
If you encounter nuxt.js + vue, or other framework problems, you can discuss and study with me in private.
You can pay attention to the favorite blog. The author will continue to update...

Guess you like

Origin blog.csdn.net/qq2754289818/article/details/126400991