Javascript 如何从函数外部节点中的https.request获取响应
我正试图做一些我无法理解的事情,我曾尝试过做一些承诺的事情,但还是被卡住了。我试着通读这篇文章,但还是被卡住了 我需要做的是运行下面的代码并将主体放在req之外,这样我就可以检查它是否成功,并发送一个带有200的lambda响应和来自主体的消息。我不想在函数中返回200状态,因为我还需要在返回带有主体的200状态之前检查获取请求是否成功 希望有人能帮上忙Javascript 如何从函数外部节点中的https.request获取响应,javascript,node.js,Javascript,Node.js,我正试图做一些我无法理解的事情,我曾尝试过做一些承诺的事情,但还是被卡住了。我试着通读这篇文章,但还是被卡住了 我需要做的是运行下面的代码并将主体放在req之外,这样我就可以检查它是否成功,并发送一个带有200的lambda响应和来自主体的消息。我不想在函数中返回200状态,因为我还需要在返回带有主体的200状态之前检查获取请求是否成功 希望有人能帮上忙 let statusTrue const req = https.request(options, function(res) { res
let statusTrue
const req = https.request(options, function(res) {
res.setEncoding("utf8")
res.on("data", function(body) {
console.log(`Body: ${body}`)
statusTrue = body.status
})
})
if (statusTrue) {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: true }),
}
} else {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: false }),
}
}
更新这是我的代码和oswins答案,是上下文的完整代码。现在,函数在处理程序完成后激发,因此我永远无法发送正确的响应
const sgMail = require("@sendgrid/mail")
require("dotenv").config()
const { SENDGRID_API_KEY, SENDGRID_TO_EMAIL } = process.env
const URL = require("url")
const https = require("https")
const fetch = require("node-fetch")
exports.handler = async (event, context) => {
try {
//console.log(JSON.parse(event.body))
//*** send off to google to verify captcha */
const body = JSON.parse(event.body)
let secret = "fdsf"
const fetchUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${body.captcha}&remoteip=${event.headers["client-ip"]}`
let isItTrue
await fetch(fetchUrl, {
method: "POST",
body: JSON.stringify({ message: "hello world" }),
headers: { "Content-Type": "application/json" },
})
.then(response => response.json())
.then(data => {
isItTrue = data.success
})
.catch(error => {
console.error("Error:", error)
})
//console.log(isItTrue)
//*** end */
//*** Running Form Sends Now if Captcha Valid */
if (isItTrue) {
//*** Zapier Send */
const webhook_url = URL.parse(
"https://hooks.zapier.com/hooks/catch/fds"
)
const options = {
hostname: webhook_url.hostname,
path: webhook_url.pathname,
method: "POST",
headers: { "Content-Type": "application/json" },
}
// Set up webhook request
const req = https.request(options, function(res) {
res.setEncoding("utf8")
res.on("data", function(body) {
console.log(`Body: ${body}`)
sendResponse(body.status)
})
})
// Handle webhook request error
req.on("error", function(e) {
const errorMessage = `[ERROR] Problem with request: ${e.message}`
console.log(errorMessage)
callback(e.message, {
statusCode: 400,
body: errorMessage,
})
})
// Send form data to webhook request and end request
req.end(JSON.stringify(body.data))
//*** End */
//console.log(zapierStatus)
const sendResponse = statusTrue => {
if (statusTrue === "success") {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: true }),
}
} else {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: false }),
}
}
}
} else {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ captcha: false }),
}
}
//*** end */
} catch (err) {
return { statusCode: 500, body: err.toString() }
}
}
您可以将您的
https.request
呼叫包装成这样的承诺:
const makeRequest = function(options) {
return new Promise(function(resolve, reject) {
const req = https.request(options, function(res) {
res.setEncoding("utf8")
res.on("error", reject)
res.on("data", function(body) {
console.log(`Body: ${body}`)
resolve(body.status)
})
})
}
之后,您可以执行以下操作:
makeRequest({/*options*/})
.then(function(statusTrue) {
if (statusTrue) {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: true }),
}
} else {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ email: false }),
}
}
})
.then(function(ret) {
console.log(ret)
})
.catch(function(err) {
/* handle error */
})
也许将函数外部的语句包装到另一个函数中会有所帮助;-)
const req=https.request(选项、函数(res){
res.setEncoding(“utf8”)
res.on(“数据”,功能(主体){
log(`Body:${Body}`)
statusTrue=body.status
sendResponse(状态为True)
})
})
函数sendResponse(statusTrue){
如果(状态为True){
返回{
状态代码:200,
标题:{
“访问控制允许来源”:“*”,
},
body:JSON.stringify({email:true}),
}
}否则{
返回{
状态代码:200,
标题:{
“访问控制允许来源”:“*”,
},
body:JSON.stringify({email:false}),
}
}
}
除非使用函数内部的技术,否则无法获得函数外部的值。按照此处的说明操作。您可以在回调函数中使用该值,或者从回调函数中调用其他函数并传递该值。这就是异步编程在Javascript中的工作方式。如果你想用一种更友好的方式来编程,您将使用支持承诺的http库,如and program with PROMITES和async/await
。我这里的问题是,我正在异步lambda函数中运行所有内容,因此函数sendResponse在lambda将响应发送回fetch请求后激发。我添加了一个upate,其中包含我的完整代码,以尝试您的应答用我的完整代码更新了我的问题,我还有几个与.req交互的函数,所以我不确定如何实现您的解决方案,我是否也将它们放在makeRequest函数中。