gpt4 book ai didi

javascript - 为什么 NodeJS 可以使用 Chain API 稍后请求设置 post 表单?

转载 作者:可可西里 更新时间:2023-11-01 16:53:57 26 4
gpt4 key购买 nike

我想弄清楚为什么我们可以在调用 request.post 之后使用 .form 设置 post 请求的表单。

这是来自官方文档的代码片段

request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}},
function(err,httpResponse,body){ /* ... */ })

我对第二个示例 request.post('http://service.com/upload').form({key:'value'}) 感到困惑。在我看来,它不应该工作,因为一旦 request.post(...) 被调用,请求就会被发送。然后调用 .form 就像您在发送请求后设置发布表单一样。那么这是如何工作的呢?有什么问题吗?

最佳答案

And then the call to .form is like you are setting the post form after the request has been sent. So how can this work ?

显然,当您这样做时:

request.post('http://service.com/upload')

请求不会立即发送。相反,它被注册(使用 setImmediate()process.nextTick())在事件循环的下一个节拍上发送。

因此,当您执行 request(...).form({key:'value'}) 时,.form() 有机会修改发送前的请求。

the doc for .post() , 有这个语句解释:

For advanced cases, you can access the form-data object itself via r.form(). This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling form() will clear the currently set form data for that request.)

在上面的语句中,r 是调用 request.post() 的返回值,所以 r.form() 指的是 request.post(...).form(...) 这是你的具体情况。

并且,在 the source code这是评论吗:

// start() is called once we are ready to send the outgoing HTTP request.
// this is usually called on the first write(), end() or on nextTick()

关于javascript - 为什么 NodeJS 可以使用 Chain API 稍后请求设置 post 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50399364/

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