Javascript 如何在Node.js中发出扩展http请求
我想在node.js中发出一个扩展请求。我的意思是,我想在另一个请求中发布数据。基本上我想给一个网站发个信息 我有以下代码:Javascript 如何在Node.js中发出扩展http请求,javascript,node.js,http,request,Javascript,Node.js,Http,Request,我想在node.js中发出一个扩展请求。我的意思是,我想在另一个请求中发布数据。基本上我想给一个网站发个信息 我有以下代码: var request = require('request') request({ method: "POST", baseUrl: "https://www.sitehere.com", uri: "/login", form: { username: "u
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); })
但它不起作用,因为在第二个请求中,我想我没有登录。我不确定这是否是问题所在,因为两个请求都返回空的body。但这是可行的(在浏览器中):
所以我想登录并保持登录以发送消息。
对不起,我的英语不好。谢谢
编辑:上面的代码以
{success:true,redirectTo:https://www.sitehere.com/“}
而我的http post请求返回的body为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语法使用承诺来避免回调地狱
更新:正如@Brad在评论中指出的,您可能还希望保留请求中的cookie,这就是我添加cookie罐的原因 您还可以使用
.then(){…}
验证登录是否成功,然后发送第二个请求。我仍然会将正文清空。我想这是因为页面重定向到另一个页面。我该怎么办?谢谢。你是对的,但这说明答案没有错,只是不完整。我会给它添加一条评论。ajax示例表明正在使用Cookie,但其他形式的登录也可能是可行的,这就是为什么我没有进一步指定在第一个请求通过后要做什么。听起来你真正需要做的是处理Cookie。这可能有效。但是现在,我需要修复第一个POST请求,然后我将尝试处理cookies。谢谢
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); })
})