[英]How to make an extended http request in Node.js
我想在 node.js 中进行扩展请求。 我的意思是,我想在另一个请求中 POST 数据。 基本上我想向网站发送消息。
我有这个代码:
var request = require('request')
request({
method: "POST",
baseUrl: "https://www.sitehere.com",
uri: "/login",
form: {
username: "username",
password: "password",
autologin: "true"}},
function(err,httpResponse,body){ console.log(body); })
request({
method: "POST",
baseUrl: "https://www.sitehere.com",
uri: "/postmessage",
form: {
message: "test"
}
}, function(err,httpResponse,body){ console.log(body); })
但它不起作用,因为在第二个请求中我没有登录,我想。 我不确定这是否是问题,因为两个请求都返回空的正文。 但这有效(在浏览器中):
$.ajax("/login",{data:{
username:"username",
password: "password",
autologin:"true"},
method:"POST"}).done(postMessage()) // here somehow I get redirected no the home page
function postMessage() {
$.ajax("/postmessage",{method:"POST",data:{message:"test"}})
}
所以我想登录并保持登录以发送消息。 对不起,我的英语不好。 谢谢。
编辑:上面的代码将正文返回为{success: true, redirectTo: "https://www.sitehere.com/"}
并且我的 http post 请求将正文返回为 null
您一开始就遇到了许多功能/问题中的第一个,这些功能/问题可能会使使用nodejs / javascript有点困惑。 您必须将第二个调用移到第一个调用的结束位置,否则,第二个调用将与第一个调用并行(异步)处理,而不是等待第一个调用。
var request = require('request')
const cookieJar = request.jar()
request({
jar: cookieJar,
method: "POST",
baseUrl: "https://www.sitehere.com",
uri: "/login",
form: {
username: "username",
password: "password",
autologin: "true"}
},function(err,httpResponse,body){
console.log(body);
request({
jar: cookieJar,
method: "POST",
baseUrl: "https://www.sitehere.com",
uri: "/postmessage",
form: {
message: "test"
}
}, function(err,httpResponse,body){ console.log(body); })
})
为了使您的生活更轻松,我建议您首先了解一下nodejs如何处理异步性,这与闭包相关的含义以及如何通过最新的async / await语法避免使用promises进行回调地狱。
更新:正如@Brad在评论中指出的,您可能还想保留请求中的cookie,这就是为什么我添加了一个cookie jar。
您可以尝试使用sync-request 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.