Vue配合Nginx部署出现404、页面无法跳转、后端请求失败问题解决方案



Vue的配置

module.exports = {
    
    
    devServer: {
    
    
        open: true,
        proxy: {
    
    
            // 接口目标地址
            "/api": {
    
    
                target: 'http://1.116.64.64:5004/api2',
                changeOrigin: true,
                // 重写路径
                pathRewrite: {
    
    
                    '/api': ''
                }
            }
        }
    }
}

Nginx的配置

常见问题有:

1、部署后,打开地址可以看到,但是刷新后出现404。
2、Vue的路由资源并不一定是真实路径,导致页面无法跳转或其他资源加载问题。
3、请求后端接口地址失败。


server {
    
    
        listen       8080;
        server_name  localhost;

        #charset koi8-r;
        #access_log  logs/host.access.log  main;

        location / {
    
    
        	# 项目地址
            root   D:\project\vue\vue_general_management_system\project-v2\dist;
            index  index.html index.htm;
            
             # 解决vue项目刷新以后变成404的问题
			try_files $uri $uri/ @router;
        }
		
		location @router {
    
    
			# Vue项目路由不是真实存在的,所以需要将请求重写到 index.html 中,然后交给真正的 Vue 路由处理请求资源
			rewrite ^.*$ /index.html last; 
		}
		
		# 请求后端失败
		location /api/ {
    
    
          # 后端的真实接口
          proxy_pass http://1.116.64.64:5004/api2/;
          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_set_header   Cookie $http_cookie;
          # for Ajax
          #fastcgi_param HTTP_X_REQUESTED_WITH $http_x_requested_with;
          proxy_set_header HTTP-X-REQUESTED-WITH $http_x_requested_with;
          proxy_set_header HTTP_X_REQUESTED_WITH $http_x_requested_with;
          proxy_set_header x-requested-with $http_x_requested_with;
          client_max_body_size 10m;
          client_body_buffer_size 128k;
          proxy_connect_timeout 90;
          proxy_send_timeout 90;
          proxy_read_timeout 90;
          proxy_buffer_size 128k;
          proxy_buffers 32 32k;
          proxy_busy_buffers_size 128k;
          proxy_temp_file_write_size 128k;
		}

		......

猜你喜欢

转载自blog.csdn.net/qq_40579464/article/details/128635020