首页 > 解决方案 > 为什么在获取请求后出现“错误空响应”?

问题描述

我的项目捆绑在 webpack 上。我有一个将数据发布到其他本地服务器的表单,其中保存在 txt 文件中。一切正常,数据正确保存,但几分钟后,客户端返回警报“net::ERR_EMPTY_RESPONSE”,然后第二次将相同的表单值保存到文件中。为什么会保存两次?如何解决这个问题。

我的获取帖子请求:

fetch("http://localhost:4000/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  },
  body: JSON.stringify(fragment),
  if(err) {
    throw err;
  }
})
  .then(console.log(fragment))
  .catch(alert); 

我的服务器:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');

app.get('/', (req, res) => {
    res.send('hello')
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors({
    allowedOrigins: [
        'http://localhost:9000'
    ]
}));

app.get('/post', (req, res) => {
    console.log(req.body)
    res.send('post')
})

app.post('/post', (req, res) => {
    res = 0;
    if (req.body.film.includes('день: Понеділок')) {
        fs.appendFile('booking.monday.txt',
            `${req.body.name},${req.body.number},${req.body.film}\n`,
            function (err) {
                if (err) throw err;
                console.log('Saved!');
            });
    }
})

标签: javascriptnode.jsexpressfetchfs

解决方案


推荐阅读