gpt4 book ai didi

javascript - 向 node.js 服务发送请求会导致超时

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

了解 Node.js 并开发了一个简单的服务:

// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port

var bodyParser = require('body-parser');
//var methodOverride = require('method-override')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
//the code hits this point!
var data = '';
req.on('data', function (chunk) {
data += chunk;
});
req.on('end', function () {
req.rawBody = data;
next();
});
//console.log(data);
});
//app.use(methodOverride());
// routes ======================================================================
require('./routes.js')(app);

// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);

routes.js

var _ = require('underscore');

module.exports = function (app) {
app.post('/', function (req, res) {
var Validator = require('jsonschema').Validator;
var v = new Validator();
var jso = req.rawBody;
var newjso = JSON.parse(req.rawBody);
var schema={
"description": "A payload",
"type": "object"
};

var result = v.validate(newjso,schema);

console.log('----------------------payload--------------------------------------')
console.log(newjso);
console.log('------------------end payload--------------------')

if (result.errors.length > 0) {
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "Could not decode request: JSON parsing failed"
});
console.log('------------------ERROR!!!--------------------')
}
else
{
var resp = _.filter(_.where(newjso.payload, {drm: true}), function (item) {
return item.episodeCount > 0
});

var newArray = [];
resp.forEach(function (item) {
var newItem = _.pick(item, 'image', 'slug', 'title');
newItem.image = _.propertyOf(newItem.image)('showImage');
newArray.push(newItem);
})

res.setHeader('content-type', 'application/json');
res.status(200);
res.json({response: newArray});
}
})
}

当我将此或任何其他 json 发布给 postman 时:

{
"payload": [
{
}]
}

指定 Contenttypeheader = application/json 时似乎超时。为什么会超时以及如何在我的 Node.js 程序中修复此问题? postman piccie

最佳答案

这是因为 bodyParser.json() 已经解析了整个请求,因此 end 永远不会在您的自定义中间件中触发。再说一遍,我不明白为什么当您所做的只是将原始请求传递给 JSON.parse() 时,您却试图捕获原始请求,这就是 bodyParser.json() 已经这样做了。

关于javascript - 向 node.js 服务发送请求会导致超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30960880/

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