【问题标题】:How to send code written in code editor to server using POST method如何使用 POST 方法将在代码编辑器中编写的代码发送到服务器
【发布时间】:2019-09-29 19:36:13
【问题描述】:

我正在构建一个 sn-p 管理器应用程序,您可以通过该界面创建新的 sn-ps 并使用代码编辑器对其进行编辑,但我遇到的问题是如何发送 sn-p 代码使用 POST 到我的服务器,以便为该 sn-p 创建一个新文件。

例如。 -

const getUser = async (name) => {
  let response = await fetch(`https://api.github.com/users/${name}`);
  let data = await response.json()
  return data;
}

我能想到的一个解决方案是将代码解析为 JSON 等价物,该等价物将包含 JSON 格式的所有标记,但为此我必须为每种语言添加解析器并根据所使用的语言选择解析器用户选择。我试图找出一种方法来避免必须添加所有解析器,除非没有任何解决方案。

我能想到的另一个解决方案是从前端生成文件并通过 POST 请求发送该文件。

我当前的堆栈是 Node+React

【问题讨论】:

    标签: node.js reactjs http


    【解决方案1】:

    使用第二种解决方案现在对我有用。我已经为它编写了下面的代码 -

    app.post("/create", isFileAttached, function(req, res) {
      const { file } = req.files;
      const saveLocation = `${saveTo}/${file.mimetype.split("/")[1]}`;
      const savePath = `${saveLocation}/${file.name}`;
      if (!fs.existsSync(saveLocation)) {
        fs.mkdirSync(saveLocation, { recursive: true });
      }
      fs.writeFile(savePath, file.data.toString(), err => {
        if (err) throw err;
        res.status(200).send({ message: "The file has been saved!" });
      });
    });
    

    有了这个解决方案,我不再需要添加任何解析器,因为文件中写入的内容不再是问题。

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 2011-03-14
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      相关资源
      最近更新 更多