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

时间:2018-12-03 23:26:20

标签: node.js reactjs filesystems

我正在尝试创建一个非常简单的Web应用程序,用户可以在其中创建要显示的Web日历上的事件。我正在使用的日历应用程序具有读取json文件以获取事件信息的功能。我已经使日历组件正常工作,并且将api设置为正确发送数据。即时消息遇到我的api的发布部分时,我在尝试处理数据时遇到问题。我将其范围缩小到了我的fs.writefile。我似乎在这里做错了。其余代码库工作正常,当我注释掉试图将要发送到/ createEvent的帖子数据的部分注释掉时,整个代码有效(减去写入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正在发送但未处理的示例帖子:

{ 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}!`))

2 个答案:

答案 0 :(得分:1)

您抛出了一个错误,但没有处理。您也不会将对帖子的回复发送回客户端。

为什么不只发送500状态而不是抛出错误?

AB

答案 1 :(得分:0)

您没有处理该错误,因此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)
}