Express 服务器不响应请求

Express server not responding to reqs

向服务器发送一堆 POST/GET 请求后,我的服务器停止响应,并且在控制台的网络选项卡中,所有请求都标记为 "pending"。

我在响应期间记录了时间戳,但它们速度很快,一旦问题发生,它们就不会 运行。

服务器:

var ip = require('ip');
var fs = require('fs');
var bodyParser = require('body-parser');
var path = require('path');
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);

var students = [];
var cons = [];

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

app.post('/add', function(req, res) {
  students.push(req.body);
  for (var i = 0; i < cons.length; i++) {
    cons[i].send(JSON.stringify(students));
  }
});
app.post('/del', function(req, res) {
  for (var i = 0; i < students.length; i++) {
    if (students[i] == req.body) {
      students.splice(i, 1);
    }
  }
  for (var i = 0; i < cons.length; i++) {
    cons[i].send(JSON.stringify(students));
  }
});
app.get('/students', function(req, res) {
  res.send(JSON.stringify(students));
});
app.ws('/mes', function(ws, req) {
  cons.push(ws);
  ws.on('close', function(req) {
    for (var i = 0; i < cons.length; i++) {
      if (cons[i] == ws) {
        cons.splice(i, 1);
      }
    }
  });
});

发件人:

function sendData() {
  if (okMes() == true) {
    console.log(student_i.value);
    fetch('/add', {
        method: 'POST',
        body: student_i.value
      })
      .catch(function(err) {
        console.error(err);
      });
    student_i.value = '';
  }
}

接收者:

function placeButton(data) {
  if (data.length == 0) {
    error_p.style.display = 'block';
    error_p.innerHTML = 'No New Students';
  }
  for (var i = 0; i < 200; i++) {
    if (document.getElementById(i) != null) {
      document.getElementById(i).remove();
    }
  }
  students = [];
  for (var i = 0; i < data.length; i++) {
    student = document.createElement('button');
    student.innerHTML = data[i];
    students_d.appendChild(student);
    students.push(student);
    student.setAttribute('id', students.length - 1);
    error_p.style.display = 'none';
  }
  for (var i = 0; i < students.length; i++) {
    students[i].onclick = function() {
      for (var i = 0; i < students.length; i++) {
        if (students[i] == this) {
          students.splice(i, 1);
        }
      }
      // document.getElementById(this.getAttribute('id')).remove();
      fetch('/del', {
        method: 'POST',
        body: this.innerHTML
      });
      if (document.querySelectorAll('button') == []) {
        error_p.style.display = 'block';
        error_p.innerHTML = 'No New Students';
      }
    }
  }
}
// seting interval and fetching for '/students' and calling this func
// reciving ws.onmessage and calling this func

我不知道为什么我的请求没有得到回应,如果有人能提供帮助那就太好了。

Fetch API 预计已满 url。将您的 fetch 呼叫更改为:

// assuming you're running on localhost on port 3000
fetch('http://localhost:3000/del', {
  method: 'POST',
  body: this.innerHTML
});

我只是在测试我的代码时找到了答案。原来我在处理 post 请求时没有 res.end(),我猜请求可能已经超时了。