vue 代理解决跨越方法

本文介绍了浏览器的跨域限制以及本地开发中使用Vue配置devServer解决跨域的方法,通过设置代理将请求转发到目标API。同时,详细讲解了在正式环境中如何利用Nginx进行跨域代理,提供了一个具体的nginx.conf配置示例,帮助开发者实现前后端分离应用的部署和跨域问题的处理。
摘要由CSDN通过智能技术生成

一、什么是跨域

跨域指浏览器不允许当前页面的所在的源去请求另一个源的数据。
源指协议,端口,域名。只要这个3个中有一个不同就是跨域。
在这里插入图片描述

列子:
#协议跨域
http://a.abc.com访问https://a.abc.com;
#端口跨域
http://a.abc.com:8080访问http://a.abc.com:80;
#域名跨域
http://a.abc.com访问http://b.abc.com;

二、本地开发解决跨域方法

在 vue.config.js 中配置devServer

module.exports = {
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'assets', // 静态资源目录 (js, css, img, fonts)
  lintOnSave: process.env.NODE_ENV !== 'production',
  devServer: { //跨域
    port: "8080", //端口号
    host: "localhost",
    open: true, //配置自动启动浏览器
    proxy: { // 配置跨域处理 可以设置多个
      '/api': {
        target: 'http://a.abc.com:8081',//跨域请求头信息
        changeOrigin: true,
        ws: false,
        secure: false, // 如果是https接口,需要配置这个参数
        pathRewrite: {
          '^/api': '/'
        }
         //pathRewrite: {'^/api': '/'} 重写之后url为 http://a.abc.com:8081/xxxx
         //pathRewrite: {'^/api': '/api'} 重写之后url为 http://a.abc.com:8081/api/xxxx
      }
    }
  }

发送请求:

axiosF(){
this.$axios.get("api/v2")
	.then(res=>{
		console.log(res)
	}).catch(err=>{
		console.log(err)
	})
}

请求http://localhost:8080/api/v2就会被代理到http://a.abc.com:8081/v2
注意请求后必须添加api否认不会被代理。可以设置 axios 的 baseURL 值
axios.defaults.baseURL = ‘/api’
这样会为所有的 请求url 前面都加上 ‘/api’,方便做 统一代理。

axiosF(){
this.$axios.get("/v2")
	.then(res=>{
		console.log(res)
	}).catch(err=>{
		console.log(err)
	})
}

三、正式环境中用nginx代理。

nginx.conf文件配置
server {
listen 80;
server_name a.abc.com;
location / {
# 这里是根目录的项目
try_files $uri $uri/ /index.html;
root /home/html/travel/dist;
index index.html index.htm;
}
     # 这里是需要部署的二级目录应用配置
location ^~/api/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://a.abc.com:8081;
}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值