错误[ERR_STREAM_WRITE_AFTER_END]:结束后写入(NodeJS)

问题描述 投票:0回答:1

我正在尝试使用nodejs创建一个api端点。当我使用邮递员到达路线时出现错误。第一次运行代码,然后服务器崩溃了。

我的代码是:

const http = require('http');
const {handleReqRes} = require('./helpers/handleReqRes');

const app = {};

app.config = {
    port: 5000,
};

app.createServer = () => {
    const server = http.createServer(app.handleReqRes);
    server.listen(app.config.port, () => {
        console.log(`listening to port ${app.config.port}`);
    });
};

app.handleReqRes = handleReqRes;

app.createServer();

在终端上,当我请求任何错误时显示:

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.end (node:_http_outgoing:968:15)
    at IncomingMessage.<anonymous> (/home/rafid/Desktop/personal_akam/Node/raw_node_api/helpers/handleReqRes.js:52:13)
    at IncomingMessage.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1358:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ServerResponse instance at:
    at emitErrorNt (node:_http_outgoing:827:9)
    at processTicksAndRejections (node:internal/process/task_queues:84:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}```


Trying to make an api endpoint using nodejs.
javascript node.js
1个回答
0
投票

明白了。我的代码中有两个

res.end
回调。
handleReqRes

const url = require('url');
const {StringDecoder} = require('string_decoder');
const routes = require('../routes');
const {notFoundHandler} = require("../handlers/routeHandlers/notFoundHandler");
const {parseJSON} = require("../helpers/utilities");

const handler = {};

handler.handleReqRes = (req, res) => {
    const parseUrl = url.parse(req.url, true);
    const path = parseUrl.pathname;
    const trimmedPath = path.replace(/^\/+|\/+$/g, '');
    const method = req.method.toLowerCase();
    const queryStringObject = parseUrl.query;
    const headersObject = req.headers;

    const requestProperties = {
        parseUrl,
        path,
        trimmedPath,
        method,
        queryStringObject,
        headersObject
    };

    const decoder = new StringDecoder('utf-8');
    let realData = '';

    const chosenHandler = routes[trimmedPath] ? routes[trimmedPath] : notFoundHandler;


    req.on('data', (buffer) => {
        realData += decoder.write(buffer);
    })

    req.on('end', () => {
        realData += decoder.end();

        requestProperties.body = parseJSON(realData);

        chosenHandler(requestProperties, (statusCode, payload) => {
            statusCode = typeof(statusCode) === 'number' ? statusCode : 500;
            payload = typeof(payload) === 'object' ? payload : {};
    
            const payloadString = JSON.stringify(payload);
    
            res.setHeader('Content-Type', 'application/json');
            res.writeHead(statusCode);
            res.end(payloadString);
        });
        
        res.end('Hello, world!');
    })
};

module.exports = handler;

© www.soinside.com 2019 - 2024. All rights reserved.