Node.js:响应是否发送给正确的用户?
假设我有一个简单的代码,它用 .XML 文件进行响应。
app.post '/incoming', (req,res) ->
console.log "Hello, incoming call!"
message = req.body.Body
from = req.body.From
sys.log "From: " + from + ", Message: " + message
test = "hello"
r = new Twiml.Response()
r.append(new Twiml.Say('Hello, there!' + test + ' Enter your ATM card PIN'))
console.log(r.toString())
res.send r.toString()
如果同时发出 2 个请求,有可能得到错误的响应吗?我问这个问题是因为我不完全理解异步是如何工作的以及这是否正在做我想要它做的事情。
谢谢
Let's say I have this simple code that responds with a .XML file.
app.post '/incoming', (req,res) ->
console.log "Hello, incoming call!"
message = req.body.Body
from = req.body.From
sys.log "From: " + from + ", Message: " + message
test = "hello"
r = new Twiml.Response()
r.append(new Twiml.Say('Hello, there!' + test + ' Enter your ATM card PIN'))
console.log(r.toString())
res.send r.toString()
Is it possible that if 2 requests come at the same time, one gets the wrong response? I'm asking this because I don't fully understand how async works and if this is doing what I want it to do.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想知道响应发送到哪个客户端,请从正文中删除除了与
res
交互的代码之外的所有代码,如下所示:现在您可以看到您发送的
r.toString()
到正确的响应。即使 2 个请求同时到来,javascript 也是单线程和阻塞的,因此永远不会有任何竞争条件。
If you want to know which client the response goes to, remove all code from the body apart from code that interacts with
res
like so :Now you can see that your sending
r.toString()
to the correct response.Even if 2 requests come at the same time, javascript is single threaded and blocking so there are never any race conditions.
你问的实际上是一个关于 CoffeeScript 范围的问题。当您有一个函数时,例如
在该函数内,您可以放心
req
和res
将始终指向传递给该函数的对象。唯一的例外是如果您有一个具有相同参数名称的嵌套函数。例如,当使用任何值调用外部函数时,都会显示
undefined
,undefined
,因为传递给setTimeout
的函数有自己的req
和res
参数遮蔽外部req
和res
。显然你没有这样做(而且你不应该这样做),所以你不必担心。您的服务器每秒可以被 ping 数万次,并且每个
req
和res
将保持不同。What you're asking is really a question about CoffeeScript scope. When you have a function, e.g.
then within that function, you can be assured that
req
andres
will always point to the objects that were passed in to the function. The only exception is if you have a nested function with the same argument names. For instance,will display
undefined
,undefined
when the outer function is called with any values, because the function passed tosetTimeout
has its ownreq
andres
arguments that shadow the outerreq
andres
.Obviously you're not doing that (and well you shouldn't), so you needn't worry. Your server can be pinged tens of thousands of times per second, and each
req
andres
will remain distinct.