发送axios post请求到快速网络服务器时的ECONNRESET

tct7dpnv  于 2023-01-09  发布在  iOS
关注(0)|答案(1)|浏览(691)

我想用axios发送一个post请求到我的web服务器。我有一个客户端,它接受用户输入来填充一个字符串数组,然后用axios发送一个post请求,由服务器处理:

if (parsedInput > 0 && parsedInput <= 8) {
          let listOfNames = [];
          for (let i=0; i<parsedInput; i++) {
            let name = await rl.question(`Enter name #${i}\n`);
            listOfNames.push(name);
            console.log(`Added ${name} to list of players\n`);
          }
          axios.post('http://localhost:3000/start', {
            names: listOfNames,
          })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
}

我的服务器虽然还没有处理请求,只是应该打印出来,它收到了来自客户端的请求:

const express = require('express');
const app = express()
const port = 3000
var listOfNames = [];
app.post('/start', async (req, res) => {
  listOfNames = req.body.names;
  console.log(listOfNames);
  res.status(200).send("Names added");
});
app.get('/', function(req, res, next) {
  res.send("Welcome to the homepage of bowling");
})
app.listen(port, () => {
  console.log('Listening to request on port 3000');
});

就在我发送名称数组时,我收到了这个ECONNRESET错误。

AxiosError: read ECONNRESET
    at AxiosError.from (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cjs:789:14)
    at RedirectableRequest.handleRequestError (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cjs:2744:25)
    at RedirectableRequest.emit (node:events:513:28)
    at eventHandlers.<computed> (C:\Users\cmb\rectangleHealth\node_modules\follow-redirects\index.js:14:24)
    at ClientRequest.emit (node:events:513:28)
    at Socket.socketErrorListener (node:_http_client:494:9)
    at Socket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  syscall: 'read',
  code: 'ECONNRESET',
  errno: -4077,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: AxiosHeaders {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'User-Agent': 'axios/1.2.2',
      'Content-Length': '18',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'post',
    url: 'http://localhost:3000/start',
    data: '{"names":["mike"]}'
  },
  request: <ref *1> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/start',
      method: 'POST',
      headers: [Object: null prototype],
      agents: [Object],
      auth: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: [Object],
      hostname: 'localhost',
      port: '3000',
      agent: undefined,
      nativeProtocols: [Object],
      pathname: '/start'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 18,
    _requestBodyBuffers: [ [Object] ],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: '18',
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [Socket],
      _header: 'POST /start HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json\r\n' +
        'User-Agent: axios/1.2.2\r\n' +
        'Content-Length: 18\r\n' +
        'Accept-Encoding: gzip, compress, deflate, br\r\n' +
        'Host: localhost:3000\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/start',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kEndCalled)]: true,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'http://localhost:3000/start',
    [Symbol(kCapture)]: false
  },
  cause: Error: read ECONNRESET
      at TCP.onStreamRead (node:internal/stream_base_commons:217:20) {
    errno: -4077,
    code: 'ECONNRESET',
    syscall: 'read'
  }

很抱歉的文本转储,不知道是否有任何有用的信息在JSON对象。我的服务器从来没有结束打印的名字列表,所以我假设它从来没有真正得到后请求。我该如何修复这个ECONNRESET错误。

rqcrx0a6

rqcrx0a61#

根据您的Express版本,您可能需要在处理程序之前使用bodyParser中间件

const express = require('express');
var bodyParser = require('body-parser')

const app = express();
app.use(bodyParser.json());
...

相关问题