【问题标题】:What's problem with my code. I am giving a curl post request but data is not showing in respose body of header我的代码有什么问题。我正在发出 curl 发布请求,但数据未显示在标题的响应正文中
【发布时间】:2020-09-06 09:51:03
【问题描述】:

此代码正在从 curl 接收数据,并假设在标题正文响应中显示该数据。但它不起作用。我哪里错了???

const server = http.createServer((req , res) => {
res.writeHead(200, {'Content-type': 'text/plain'});
const { headers, method, url } = req;
let body = [];
req.on('error', (err) => {
    console.error(err);
  })
req.on('data', (chunk) => {
body.push(chunk);
})
req.on('end', () => {
    body = Buffer.concat(body).toString();
});

});

【问题讨论】:

  • 嗨,您能否添加curl 命令并添加有关您要激活的内容的更多信息?
  • ' curl --location --request POST 'localhost:3000' \ --header 'Content-Type: text/plain' \ --data-raw '现在都在一起了!' '
  • 这是 curl 命令。我只想显示“现在都在一起!”通过此命令在标头正文响应中
  • header body response 是什么意思?有一个由标头和正文构建的 HTTP 响应。你在哪里设置All together now!

标签: node.js curl echo-server


【解决方案1】:

如果您在响应正文中设置All together now!,这应该可以完成工作。

const http = require('http');

const server = http.createServer((req, res) => {
    let body = [];
    req.on('error', (err) => {
        console.error(err);
    })
    req.on('data', (chunk) => {
        body.push(chunk);
    })
    req.on('end', () => {
        body = Buffer.concat(body).toString();

        // set response
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(body);
    });
});

server.listen('3000');

【讨论】:

  • @tsm009 请选择答案。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2017-12-29
  • 2015-04-06
相关资源
最近更新 更多