尝试从文本文件中读取 JSON 并发送 post 请求。位置 1

问题描述 投票:0回答:0

我在页面上有一个文件输入元素。我选择一个 JSON 文件,然后使用 FileReader 读取内容。然后我想在发布请求中发送内容。我觉得我已经尝试了标头参数和解析/字符串化文件阅读器结果的所有可能组合,但我要么在我的 req.body 中得到一个空体,要么我得到错误:

SyntaxError:位置 1 的 JSON 中的意外标记 o

我知道还有很多关于此的其他帖子,我已经浏览了所有这些帖子,但我不知道我做错了什么。

// This function is called when the user clicks the upload button after selecting a json file.
 // It reads the contents of the JSON file 
 const upload = async () => {

  var fileReader = new FileReader();
  const data = fileReader.onload = function(e){

    let data = JSON.parse(e.target.result);

    const URL = '/upload';

  fetch(URL, {method: 'POST', headers: {'Content-Type' : 'application/json'}, body: {data}}).then((response) => {
    if(!response.ok){
      throw new Error('Something went wrong')
    }     
  }
  )
  .catch((e) => {
    console.log(e)
  });
  }
  fileReader.readAsText(document.querySelector("#input").files[0], 'UTF-8');

 } 

这是服务器代码

app.use(express.json());

// Empty the database and reupload new questions from a JSON file
app.post('/upload',  async (req, res) => {

    // Create client object and wait for connection
    const client = new MongoClient(URL);
    await client.connect();

    // Set database
    const db = client.db('trivia');

    // Remove all data from the database
    db.collection('questions').deleteMany();

    // Repopulate database with new questions
    console.log(req.body);
})

我试过在解析之后、字符串化之后、两者之后发送数据。我不确定我应该以什么形式发送它。现在基于语法错误它被作为 JSON 对象发送?数据是一个 JSON 对象数组:

[{}, {}, {}] (this format)
javascript reactjs json post header
© www.soinside.com 2019 - 2024. All rights reserved.