如何响应Node.js中的发布请求?

时间:2020-08-22 13:30:30

标签: javascript node.js

我的客户端代码类似于:

let data = "Some data";

let request = new XMLHttpRequest();
let link = new URL("http://someurl.com");
link.searchParams.set("data", data);

request.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    //some code
  }
}
request.open("POST", link, true);
request.send();

如何使用node.js在服务器上检索“数据”?

2 个答案:

答案 0 :(得分:1)

解决方案并不简单。 首先,您应该使用createServerhttp之一的本地库中的https。另外,您应该知道streamevents在Node.js中的工作方式

const https = require('https');
const srv = https.createServer(...);

const SRV_HOST = '127.0.0.1';
const SRV_PORT = 5000;
const MAX_PAYLOAD = 2048;

// You should provide your custom code for these events
srv.on('connection', onClientConnection);
srv.on('request', onClientRequest);
srv.on('clientError', onClientError);
srv.on('close', onServerClose);

// Start listening...
srv.listen(SRV_PORT, SRV_HOST, onStartListening);

function onClientRequest(req, res) {
    const connectionId = `${req.client.remoteAddress}:${req.client.remotePort}`;
    const dataPocket = {
        chunks: [],
        bytes: 0
    };

    req.on('data', chunk => onClientData.call(req, res, chunk, dataPocket));
    req.on('end', onClientEnd.bind(this, req, res, dataPocket));
    req.on('error', onClientRequestError);
    res.on('close', onClientClose.bind(res, connectionId));
}

function onClientData(res, chunk, dataPocket) {
    dataPocket.bytes += chunk.length;

    if (dataPocket.bytes <= MAX_PAYLOAD) {
        dataPocket.chunks.push(chunk);
    } else {
        const message = `Data limit exceeded. Maximum ${MAX_PAYLOAD} bytes are expected`;
        const error = new Error(message);
        error.code = 'ECONNRESET';
        return this.emit('error', error);
    }
}

function onClientEnd(req, res, dataPocket) {
    const data = collectData(req, dataPocket.chunks);

    // Process your data here
    const responseData = { success: true, data: data };
    const jsonData = JSON.stringify(responseData);

    // Set headers and status
    res.setHeader('Content-Type', 'application/json');
    res.statusCode = 200;

    // Send data
    res.end(jsonData);

    // Cleanup data
    dataPocket.chunks = [];
    dataPocket.bytes = 0;
}

您可以在我的GitHub profile

中查看示例

答案 1 :(得分:1)

您可以使用http包。现在,您可以在流上使用异步迭代器。这使得读取数据和错误处理更加容易,并且不太可能导致内存泄漏。

const { createServer } = require('http');

createServer(function (req, res) {
  if (req.method === 'POST') {
    req.setEncoding('utf-8');
    (async (readable) => {
      for await (let chunk of readable) {
        // do here with the data what you want
        console.log(chunk);
      }
      res.writeHead(201);
      res.end();
    })(req).catch((err) => {
      res.writeHead(500);
      return res.end(JSON.stringify(err));
    });
  } else {
    res.writeHead(404);
    res.end()
  }
}).listen(8080);

如果您希望将输出传递到另一个流,则也可以使用pipeline method

您也可以选中this repl以获得实时演示。