首页 > 解决方案 > 如何从服务器发送一组 json 文件?

问题描述

我正在使用 vue.js。我已经编写了以下代码,但它不起作用,我该如何解决?

这是我的代码:

 mounted(){
    fetch('/', {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin    
    headers: {
       'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
   
  })
    .then(response => response.json())    
    .then(json => this.firstWindow = json)
    
    // .then(json => console.log(json))
    // .then(console.log(this.firstWindow))
    
  },

服务器部分在这里

router.post('/',(req, res) =>{  // request for sending file
    console.log("POST");
    // res.sendFile(myModule.dataOfScreens);
    res.sendFile(path.resolve('./data/firstScreen.json'));
})

标签: javascriptnode.jsvue.js

解决方案


您正在尝试从服务器获取文件,但您使用的是POST方法!!!

如果这是你想要做的,那么你应该做这样的事情:

router.get('/filesFolder?:fileName', function(req, res){
    let filePath = '.. the path of your local files folder ..+ '/' +req.query.fileName
    if (fs.existsSync(filePath)) {
      //file exists
      res.sendFile(filePath);
    }
  });

其中 filesFolder 是您存储文件的文件夹名称;fileName 是您请求的文件的名称;filePath 是请求文件的 filesFolder 下的路径。


推荐阅读