vue工程 npm run build 后把dist包放到 nginx代理服务器的html目录,在conf/nginx.conf配置文件中增加配置,这样就可以正常方位后端接口了,配置如下:

server {
    listen  8193;
    server_name  localhost 127.0.0.1;
    location / {
        root D:\agent\html;
        index  index.html  index.htm;
    }
}

vue工程中 配置后端IP地址如下:

const instance = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '/api' : '192.168.1.128:8185',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

在浏览器中输入  localhost:8193  打开前端网页,但出现了后端接口请求跨域问题。原因是localhost:8193  和发送的后端请求192.168.1.128:8185 IP 和 端口都不同,所以出现了跨域。

我们在nginx上配置转发就可以解决此跨域问题,修改步骤如下:

1. 在nginx代理服务器配置文件中配置上转发,配置如下:

server {
    listen  8193;
    server_name  localhost 127.0.0.1;
    location / {
        root D:\agent\html;
        index  index.html  index.htm;
    }

    location /file/get {
        proxy_pass http://192.168.1.128:8151;
    }
}

发送后端接口/file/get 会被转发到后端192.168.1.128:8151

2. 修改vue工程中的后端接口地址 和 打开前端页面的地址相同,如下所示:

const instance = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '/api' : 'localhost:8193',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

这样打开前端网页的地址和请求后端接口的地址相同,浏览器就不会报跨域请求错误了。而接口通过nginx 又被转发到正确的后端接口地址,所以接口就能正常访问了。

更多推荐