javascript - 如何从服务器发送一组 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'));
})
解决方案
您正在尝试从服务器获取文件,但您使用的是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 下的路径。
推荐阅读
- node.js - 基于 Node.js 和 AWS 开发全栈应用程序时的推荐实践
- excel - 根据 Excel 中的日期范围返回单元格的值
- swiper - Swiperjs 淡入淡出过渡没有正确交叉淡入淡出,而是添加了白色交叉过渡效果
- windows - 在 Mattermost 上运行服务器时出现 Unicode 错误?
- android - 运行 Gradle 任务“assembleDebug”。(这需要很长时间。)
- amazon-web-services - 使用 AWS Toolkit for Cloud9 在本地导入、编辑和调试 Lambda 函数
- java - Spring Boot 5 中的持久化 API 令牌
- typescript - Nest.js Graphql Nested InputType 抛出引用错误
- azure - 如何使用其他 Azure 服务对 IoT Central 设备进行身份验证?(例如:下载OTA bin)
- c# - 文档 | 为什么 API 返回“资源不支持 http 方法 'POST'” | C#