尝试在节点中使用 API 写入文件时出现 UnhandledPromiseRejection

UnhandledPromiseRejection when trying to write to file using API in node

我正在尝试创建一个非常简单的 Web 应用程序,用户可以在其中在要显示的 Web 日历上创建一个事件。我使用的日历应用程序能够读取 json 文件以获取事件信息。我已经让日历组件正常工作,并且 api 已设置为正确发送数据。当数据到达我的 api 的 post 部分时,我在尝试处理数据时遇到了问题。我已经将范围缩小到我的 fs.writefile。我似乎在这里做错了什么。代码库的其余部分工作正常,当我注释掉我尝试写入发送到 /createEvent 的 post 数据的部分时,整个代码有效(减去写入我的 json 的预期目标文件)

这是我得到的错误:

(node:12756) [DEP0018] DeprecationWarning: Unhandled promise rejections are `deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.`

这是我的 API 正在发送但未能处理的示例 post:

{ userInput: { title: 'Vinny', start: '2018-12-01', end: '2018-12-01' } }

这是我的代码:

const express = require('express');
const routes = require('./routes/');
const app = express();
const port = 3000;
const router = express.Router();
const cors = require('cors');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const fs = require('fs')
import ('./calendarevents.json');
routes(router);
app.use(cors()); // Allows for Cross origin requests
app.use(bodyParser.json()) // Turns all post requests to json
app.use(bodyParser.urlencoded({ extended: false }));
app.use(helmet()); // Helps secure apps with Http headers

app.use('/api',router); 

app.get('/', (req, res) => res.send('Hello World!'))

app.use(bodyParser.json())


app.get('/api/createEvent'), (req, res) => {
 res.render(req.body)
}

app.post('/api/createEvent', (req, res) => {
  console.log(req.body);
  //res.send("recieved your request!")

  const UserInput = JSON.stringify(req.body);
  fs.writeFile('./calendarevents.json', UserInput, (err) => {
  if (err) throw err; 
  console.log("The file was saved!");

  });

});

  app.listen(port, () => console.log(`StoreUI Backend listening on ${port}!`))

您没有处理错误,因此 node 发出弃用警告。此外,您使用的是 import ('./calendarevents.json');,这是无效语法(除非您的 API 包含在 webpack 中——但是,我也不确定您为什么要导入它) .并且...您当前的设置将在每次发送新事件时完全覆盖 JSON 文件。如果要附加它,请参阅选项 2。

下面不是很干净,但是如果将 fs 调用包装在 promises 中,您可以清理它。为了简单起见,我决定不这样做。

选项 1:

app.post('/api/createEvent', (req, res) => {
  const calanderEventPath = './calendarevents.json';
  const newEvent = JSON.stringify(req.body);

  try {
    const pathExists = fs.existsSync(calandEventPath); // check if path exists
    if (!pathExists) throw "The calandar JSON file has not been created yet.";

    let error;
    fs.writeFileSync(calanderEventPath, newEvent, 'utf-8' function(err) { // attempts to save newEvent to the calandar JSON path
      if (err) error = 'Unable to save the new event to the calandar JSON file.';
    });

    if (error) throw error;

    res.status(201).send("Successfully saved the event.");
  } catch (err) {
    res.status(500).send(err);
  }
});

选项 2:

app.post('/api/createEvent', async (req, res) => {
  const newEvent = JSON.stringify(req.body);   
  const calanderEventPath = './calendarevents.json';      
  let savedEvents;
  let error;

  try {
    const pathExists = fs.existsSync(calandEventPath); // check if path exists
    if (!pathExists) throw "The calandar JSON file has not been created yet."; 

    fs.readFileSync(calanderEventPath, 'utf8', function(err, currentEvents) { // attempt to read file to extract current event data
      if (err) error = "Unable to read the calandar JSON file.";

      savedEvents = JSON.stringify(currentEvents.push({ newEvent })); // push "newEvent" data into the current event data and set it to "savedEvents"
    }

    if (error) throw error;    

    fs.writeFileSync(calanderEventPath, savedEvents, 'utf8', function(err) { // attempts to save "savedEvents" to the calandar JSON path
      if (err) error = 'Unable to save the new event to the calandar JSON file.';
    });

    if (error) throw error; 

    res.status(201).send("Successfully added an event");
  } catch (err) {
    res.status(500).send(err)
}  

你抛出了一个错误,但没有处理它。您也没有将对 post 的响应发送回客户端。

与其抛出错误,不如发送 500 状态?

app.post('/api/createEvent', (req, res, next) => {
    console.log(req.body);

    const UserInput = JSON.stringify(req.body);
    fs.writeFile('./calendarevents.json', UserInput, err => {
        if (err) {
            res.sendStatus(500);
        }
        else {
            console.log("The file was saved!");
            res.status(200).send("received your request!");
        }   
    });
});