1. 跨域的三种方式

1.1 jsonp

以前的技术,通过<script>标签跨域请求,服务器端返回的是符合js语法的函数调用,函数的形参即数据

1.2 CORS

跨域资源共享,需要服务器端进行配置

//express中配置cors
const cors = require("cors")
app.use(cors())

1.3  服务器代理

(1) 通过在vue.config.js中配置proxy实现跨域 (开发阶段)

(2) 通过Nginx服务器代理实现跨域 (生产阶段)

## 2. Nginx服务器代理

Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器
可以实现vue项目中的跨域请求

我们真实的服务器不应该直接暴露到公网上去,否则更加容易泄露服务器的信息,也更加容易受到攻击。一个比较“平民化”的方案是使用Nginx反向代理它。

一台具有公网的Nginx服务器可以代理和它能进行内网通信的真实的服务器。让我们的服务器不直接对外暴露,增加其抗风险能力。

2.1 下载

http://nginx.org/en/download.html|  nginx/Windows-1.10.3 |

2.2 nginx在windows系统中如何启动、重启、停止

在nginx文件夹中打开cmd

(如果是powershell不能直接使用cmd命令:  输入cmd回车即可)

//基本命令操作:
nginx -v //查看nginx的版本号
start nginx  //启动nginx
nginx -s stop //快速停止或关闭nginx
nginx -s quit //正常停止或关闭nginx
nginx -s reload //配置文件nginx.conf修改重装载命令

2.3 启动nginx

start nginx
在地址栏输入: localhost:80即可打开默认首页

2.4 修改前端vue项目中的url

在config.js中修改baseURL

//原设置
baseURL: 'http://localhost:3000'
//修改为
baseURL: '/api'

2.5 打包vue项目

npm run build
把dist文件夹放在nginx根目录

2.6 修改nginx的 conf/nginx.conf

server {
      listen       80;  #nginx服务器端口
      server_name  localhost;  #nginx域名
      location / {
          root   dist; #首页所在文件夹
          index  index.html index.htm;
      }
      location /api/ {
         proxy_pass   http://127.0.0.1:3000; # 将/api/开头的url转向该域名
         rewrite "^/api/(.*)$" /$1 break; 最终url中去掉/api前缀
      }
  }

2.7 重载nginx,浏览

nginx -s reload

3000端口的服务器要打开

2.8 vue中history模式的服务器端配置

vue中设置history模式

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes,
  mode: 'history'
})

修改nginx的conf/nginx.conf

try_files $uri $uri/ /index.html;

代码如下:

server {
    listen       80;  #nginx服务器端口
    server_name  localhost;  #nginx域名
    location / {
        root   dist; #首页所在文件夹
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    location /api/ {
       proxy_pass   http://127.0.0.1:3000; # 将/api/开头的url转向该域名
       rewrite "^/api/(.*)$" /$1 break; //最终url中去掉/api前缀
    }
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。