【问题标题】:Accessing local json files from the browser using NodeJs backend使用 NodeJs 后端从浏览器访问本地 json 文件
【发布时间】:2022-01-23 22:35:39
【问题描述】:

我正在开发一个反应应用程序,该应用程序将 json 文件路径作为参数以在我的 ui 中呈现 json 数据。从浏览器访问本地文件受到限制,那么如何创建后端服务器来检索我的本地 json 文件并将它们提供给浏览器?

【问题讨论】:

  • 这里所说的“本地”是指浏览器计算机还是服务器计算机上的文件?
  • 浏览器计算机上的@Joe

标签: javascript node.js reactjs json swagger-ui


【解决方案1】:

您可以使用 express 启动本地服务器,并使用 fs 模块访问文件内容

const fs = require('fs');
const file_content = fs.readFileSync('./{file_name}', 
    '{content_formate}').toString();

// For show the data on console
console.log(file_content);

要创建一个监听 3000 端口的服务器,请使用

const express = require('express')
const fs = require('fs');
const app = express()
const port = 3000

app.get('/', (req, res) => {


  const file_content = fs.readFileSync('./{file_name}', 
    '{content_formate}').toString();
  res.send(file_content)
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

类似的东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 2019-04-04
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多