【发布时间】:2016-06-18 18:54:54
【问题描述】:
有什么方法可以让 Express 服务器并行处理多个 GET 请求?
考虑这个例子:
server.js
var express = require('express')
var app = express();
app.get('/test01', function (req, res, next) {
for (i = 0; i < 1000000000; i++) {
var temp = i*i;
}
res.end('{"success" : "test01", "status" : 200}');
});
app.get('/test02', function (req, res, next) {
for (i = 0; i < 1; i++) {
var temp = i*i;
}
res.end('{"success" : "test02", "status" : 200}');
});
app.listen(8081, function () {
console.log("server listening at %s:%s", this.address().address, this.address().port)
})
client.js
var request = require("request");
request("http://127.0.0.1:8081/test01", function(error, response, body) {
console.log(body);
});
request("http://127.0.0.1:8081/test02", function(error, response, body) {
console.log(body);
});
运行client.js后,输出为:
{"success" : "test01", "status" : 200}
{"success" : "test02", "status" : 200}
这意味着第二个请求必须等待第一个请求完成。
为了使两个请求并行运行并使“test01”非阻塞服务并在 test01 之前完成 test02,我需要在 server.js 中进行哪些更改?
我不想更改 client.js 中的任何内容,也无法控制调用服务的时间。例如 test01 可能会被依次调用 3 次,然后 test02 可能会被调用。
【问题讨论】:
-
我的情况不同,我无法控制每次服务调用的时间。
-
如果这会像你描述的那样工作,那么整个 Node.js 平台将毫无用处。我找不到任何理由为什么响应应该按这个顺序出现。你真的尝试过运行这个确切的代码吗?
-
是的,我创建了这个小例子并运行它以便更清楚地了解我的问题。
标签: javascript node.js rest express