gpt4 book ai didi

javascript - 我传入的信息到哪里去了?

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:18 25 4
gpt4 key购买 nike

我有这个 Node http服务器。

/**
* Module dependencies.
*/

var http = require('http'),
fs = require('fs'),
cycle = require('./cycle.js');

/**
* Create the server.
*/

var server = http.createServer(function (req, resp) {
console.log(JSON.decycle(req) );
if ('GET' === req.method && '/images' === req.url.substr(0, 7) &&
'.jpg' === req.url.substr(-4) ) {
fs.stat(__dirname + req.url, function (err, stat) {
if (err || !stat.isFile() ) {
res.writeHead(404);
res.end('Not Found');
return;
}
serve(__dirname + req.url, 'application/jpg');
});
} else if ('GET' === req.method && '/' === req.url) {
serve(__dirname + '/index.html', 'text/html');
} else {
resp.writeHead(404);
resp.end('Not found');
}

function serve(path, type) {
resp.writeHead(200, {'Content-Type': type});
fs.createReadStream(path).pipe(resp);
}
});

/**
* Listen.
*/

server.listen(3000);

(它使用 Crockford 的对象打印实用程序。 https://github.com/douglascrockford/JSON-js/blob/master/cycle.js )

当我使用此请求时,我传入的信息项不会出现在请求中。为什么不呢?

RickH$ curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Cache-Control: no-cache" -H "Postman-Token: 647062e3-bd38-edf0-3b3a-e56227daf94c" -d '&first_name=James&last_name=Taylor&city=Urbana&state=Illinois' "localhost:3000"
RickH$

这是一个较大项目的精简版本。在较大的项目中,请求通过管道传送到另一台服务器,该服务器根据请求的内容使用react。所以我觉得我知道内容正在被传达。但它在哪里呢?

稍后----------------

/*********
Version 2 of server callback function. This one shows the full request body.
var server = http.createServer(function (req, resp) {
console.log();
console.log('=========================%==========================');
console.log();
console.log(JSON.decycle(req) );

req.rawBody = '';
req.setEncoding('utf8');

req.on('data', function (chunk) {
req.rawBody += chunk;
// next();
});

req.on('end', function () {
console.log();
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~~~~~~~~~~~~');
console.log();
console.log(JSON.decycle(req) );
// next();
});

if ('GET' === req.method && '/images' === req.url.substr(0, 7) &&
'.jpg' === req.url.substr(-4) ) {
fs.stat(__dirname + req.url, function (err, stat) {
if (err || !stat.isFile() ) {
res.writeHead(404);
res.end('Not Found');
return;
}
serve(__dirname + req.url, 'application/jpg');
});
} else if ('GET' === req.method && '/' === req.url) {
serve(__dirname + '/index.html', 'text/html');
} else {
resp.writeHead(404);
resp.end('Not found');
}

function serve(path, type) {
resp.writeHead(200, {'Content-Type': type});
fs.createReadStream(path).pipe(resp);
}
});
*********/

最佳答案

您需要以下代码来获取请求的正文(您的信息)

var data;
req.on('data', function(chunk){
data += chunk;
});
req.on('end', function(){
console.log(data);
});

关于javascript - 我传入的信息到哪里去了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39795666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com