我是 Node JS 的新手。请帮助我了解我在 POST 请求中做错了什么。有时我的 POST 请求得到成功解决,但有时它给了我 ECONNRESET。
我正在分享我的 app.js 和文件阅读器包装模块。
GET 运行良好。
下面是我的 App.js
const express = require('express');
const FileReader = require('./readFS');
const app = express();
const FS = new FileReader();
const port = 3000;
app.listen(3000, '127.0.0.1', () => {
console.log(`App running on port ${port}`);
});
app.use(express.json());
app.get('/api/v1/tours', (request, response) => {
const data = FS.read(`${__dirname}/dev-data/data/tours-simple.json`).then(
(data) => {
response.status(200).json({
status: 'success',
results: data.length,
data: {
tours: data,
},
});
}
);
});
app.post('/api/v1/tours', (request, response) => {
(async (req, res) => {
const tours = await FS.read(`${__dirname}/dev-data/data/tours-simple.json`);
const newID = tours[tours.length - 1].id + 1;
const newTour = Object.assign({ id: newID }, req.body);
tours.push(newTour);
console.log('File written Started');
await FS.write(
`${__dirname}/dev-data/data/tours-simple.json`,
JSON.stringify(tours)
);
console.log('File written Successfully');
res.status(200).send('Created Succesfully');
})(request, response);
});
文件阅读器模块:
module.exports = class {
constructor() {
this.tours = [];
}
read(path) {
return new Promise((resolve, reject) => {
if (this.tours.length > 0) {
resolve(this.tours);
}
fs.readFile(path, 'utf-8', (err, data) => {
if (err) reject(er);
this.tours = Object.assign(JSON.parse(data));
resolve(this.tours);
});
});
}
write(path, data) {
return new Promise((resolve, reject) => {
if (data.length <= 0) reject('Data is empty');
fs.writeFile(path, data, (err) => {
if (err) reject('Could not write');
resolve('Done');
});
});
}
};