如何捕捉服务器响应?
how to catch a server response?
有一个客户端正在向我的网络服务器发送请求。此服务器应使用数据或特定代码进行响应,例如 117 (是的,这是一个光环引用 :D) 现在我需要访问响应的数据或代码。我怎么会意识到这一点?我在 Whosebug 上没有找到类似的东西,你能帮忙吗?
客户端示例:
function sendRequest() {
var options = {
host: 'localhost',
port: 1309,
path: '/examplePath?param='+param,
param: "example"
};
http.get(options, function(resp){
resp.on('data', function(chunk){
console.log("chunk :",chunk);
});
}).on("error", function(err){
console.log("Error: " + err.message);
});
}
应答服务器:
function examplePathFunction(req,res) {
if(condition) {
//TODO Server must answer with data
} else {
//TODO Server must answer with status 117
}
}
: res.end(date/code);
可以解决我的问题吗?我如何捕捉到这个响应?
我想你正在寻找:
function examplePathFunction(req, res, next) {
if(req.body.data) {
res.status(200).send({ data: req.body.data });
return next();
} else {
res.status(117);
return next();
}
}
尽管如果您尝试通过参数发送数据,请查看那里而不是请求正文。
阅读有关 Express 的更多信息 API:http://expressjs.com/en/api.html#req
有一个客户端正在向我的网络服务器发送请求。此服务器应使用数据或特定代码进行响应,例如 117 (是的,这是一个光环引用 :D) 现在我需要访问响应的数据或代码。我怎么会意识到这一点?我在 Whosebug 上没有找到类似的东西,你能帮忙吗?
客户端示例:
function sendRequest() {
var options = {
host: 'localhost',
port: 1309,
path: '/examplePath?param='+param,
param: "example"
};
http.get(options, function(resp){
resp.on('data', function(chunk){
console.log("chunk :",chunk);
});
}).on("error", function(err){
console.log("Error: " + err.message);
});
}
应答服务器:
function examplePathFunction(req,res) {
if(condition) {
//TODO Server must answer with data
} else {
//TODO Server must answer with status 117
}
}
: res.end(date/code);
可以解决我的问题吗?我如何捕捉到这个响应?
我想你正在寻找:
function examplePathFunction(req, res, next) {
if(req.body.data) {
res.status(200).send({ data: req.body.data });
return next();
} else {
res.status(117);
return next();
}
}
尽管如果您尝试通过参数发送数据,请查看那里而不是请求正文。
阅读有关 Express 的更多信息 API:http://expressjs.com/en/api.html#req