vue前后端分离开发解决跨域的问题

开发时配置vue.config.js解决跨域

module.exports = {
    devServer: {
        port: 8080,
        host: "0.0.0.0",
        https: false,  // 协议
        open: true,  // false 启动服务时自动打开浏览器访问
        proxy: {
            '/admin': {
                target: "http://admin.caorulai.com",
                changOrigin: true,  // 是否要代理
                pathRewrite: {
                    '^/admin': '/'
                }
            }
        }
    },
    publicPath: "./",
    outputDir: "dist",
    assetsDir: "static",
    indexPath: "index.html"
}

开发完毕部署到Nginx服务器,则配置反向代理

location /admin/ {
	proxy_set_header Host $proxy_host;
	proxy_set_header  X-Real-IP        $remote_addr;
	proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
	proxy_set_header X-NginX-Proxy true;
	proxy_pass 'http://admin.caorulai.com/';
}

如果后端服务有前缀,如http://admin.caorulai.com/admin/account/login,则配置如下

location /admin/ {
	proxy_set_header Host $proxy_host;
	proxy_set_header  X-Real-IP        $remote_addr;
	proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
	proxy_set_header X-NginX-Proxy true;
	proxy_pass 'http://admin.caorulai.com';
}

你可能感兴趣的:(前端,php,js,vue,nginx,web)