前端访问服务器文件

首先说明一点前端是不能直接访问服务器上面的文件的
如果想要在前端直接访问到服务器的文件需要通过nginx做一下转发,这样才能直接访问
比如我直接在服务器上的/data内新建code-generator/blocks/test/index.vue文件,

1631100125(1).jpg

那么我想在前端直接下载这个文件,怎么办?

  • 其实这个时候如果你会后端的话,可以把code-generator/blocks/test/index.vue内容读成流然后输出到前端
  • 如果直接不经过后端,想直接下载的话,需要通过nginx来配合

nginx配置访问文件端口

server {
        listen  5676;
        server_name localhost;

        location / {
            root  /data/code-generator;   # 此处对应的是 服务器存放文件的地址
            charset  utf-8;
            try_files $uri $uri/ /index.html;
            index index.html index.htm;
            autoindex on;
            autoindex_exact_size off;
            autoindex_localtime on;
        }

    }

这个时候你直接在浏览器上输入 服务器ip:端口 ex: 127.0.0.1:5676
由于我的blocks文件内是一个test文件,就会看到如下效果


1631097503(1).png
  • 比如服务器上面的文件地址是/data/code-generator/blocks/test/index.vue,通过window.location.href下载,如果是文件夹的话是则不能通过window.location.href下载,除非把文件夹弄成压缩包
window.location.href = 'http://121.5.217.54:5676/blocks/test/index.vue'

跨域

axios或者fetch去调用的话会存在跨域问题,还需要配置一下跨域的问题

  • 跨域配置
    在指定server端口下新增配置,比如8000
server {
        listen       8000;
        ......
        location /blocks {
            proxy_pass http://localhost:5676/blocks;
            add_header 'Access-Control-Allow-origin' '*';
        }
}
fetch('http://具体ip:8000/blocks/test/index.vue').then(async res=> {
      const text = await res.text()
      console.log(text)
    })

如果是腾讯云服务器记得开防火墙端口


1641545678(1).png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容