代码之家  ›  专栏  ›  技术社区  ›  Vincent Morris

尝试在节点中使用API写入文件时未处理PromiserExjection

  •  0
  • Vincent Morris  · 技术社区  · 7 年前

    我正在尝试创建一个非常简单的web应用程序,用户可以在web日历上创建要显示的事件。我使用的日历应用程序能够读取json文件以获取事件信息。我已经让calendar组件正常工作,并且api已经设置为正确发送数据。当数据到达api的post部分时,我在处理数据时遇到了问题。我已经缩小了范围,特别是我的fs.writefile。我好像做错了什么。代码库的其余部分工作正常,当我注释掉试图将post数据发送到/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.`
    

    { 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 回复  |  直到 7 年前
        1
  •  1
  •   Jim B.    7 年前

    您正在抛出错误,但没有处理它。您也没有将对帖子的响应发送回客户端。

    与其抛出一个错误,为什么不发送一个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!");
            }   
        });
    });
    
        2
  •  0
  •   Matt Carlotta    7 年前

    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);
      }
    });
    

    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)
    }