我正在尝试使用简单的app.js(node.js)在Micro BOSH上进行REST调用。这涉及通过HTTPS在端口25555上调用url进行身份验证,并且不对SSL认证进行验证。我找到了通过HTTPS.request
或HTTPS.get
获取JSON结果的方法。
问题是我和我想使用express作为Web服务器。现在,我在执行这两项操作时获得了以下错误(我的https.request
是app.get('/', function(req, res) {...})
之外的函数的一部分:
Error: Can't remove headers after they are sent.
at ServerResponse.OutgoingMessage.removeHeader (http.js:718:11)
at ServerResponse.send (/Users/dev/bes/bes-rest/node_modules/express/lib/response.js:179:10)
at /Users/dev/bes/bes-rest/app.js:95:7
at Layer.handle [as handle_request] (/Users/dev/bes/bes-rest/node_modules/express/lib/router/layer.js:82:5)
at next (/Users/dev/bes/bes-rest/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/dev/bes/bes-rest/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/dev/bes/bes-rest/node_modules/express/lib/router/layer.js:82:5)
at /Users/dev/bes/bes-rest/node_modules/express/lib/router/index.js:235:24
at Function.proto.process_params (/Users/dev/bes/bes-rest/node_modules/express/lib/router/index.js:313:12)
at /Users/dev/bes/bes-rest/node_modules/express/lib/router/index.js:229:12
我感觉到因为我使用快速组合与http(创建服务器)然后https用于REST调用,应用程序正在以这种方式做出反应。但是在使用Express时如何才能最好地进行REST调用?
以下是我正在使用的内容:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var request = require('request');
var path = require('path');
var https_er = require('https');
感谢您提供任何暗示。
以下是我用来进行REST调用的代码:
var _deployments = {};
function getDeployments() {
var options = {
host: resturl,
port: restport,
path: '/deployments',
method: 'GET',
rejectUnauthorized: false,
requestCert: true,
agent: false,
headers: {
'Authorization': 'Basic ' + new Buffer(rest_uname + ':' + rest_pword).toString('base64')}
};
var req = https_er.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
_deployments = body;
})
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
}
到目前为止这是app.get:
app.get('/', function(req, res) {
res.send('Hello!');
res.send(JSON.parse(_deployments)); // this is the line 95
});
server.listen(port);
答案 0 :(得分:1)
你不能有两个" res.send"语句。
// one of these two statements has to go
res.send('Hello!');
res.send(JSON.parse(_deployments));
答案 1 :(得分:0)
您可以执行以下操作: -
app.get(' /',function(req,res){
res.send({" _deployments":JSON.parse(_deployments)});
}); server.listen(端口);