gpt4 book ai didi

node.js - Node js request.post 回调未触发

转载 作者:太空宇宙 更新时间:2023-11-04 00:29:53 24 4
gpt4 key购买 nike

我正在尝试将一些 JSON 数据从 Node js 应用程序发送到另一个用 Flask 编写的 Web 服务。我正在尝试使用请求库并查看了问题 herehere .

根据示例,我想出了以下简单的应用程序。该应用程序将 JSON 数据发送到我的 Flask 服务器,但不获取/触发回调。我已经检查 Flask 应用程序通过 postman 返回了一些数据而且效果很好。我哪里错了?

[这是我的整个 app.js]

  var express = require("express");
var request = require('request');
var app = express();

app.set('view engine', 'pug');
app.get('/', function(req, res) {
console.log("here...")
request({
url: 'http://localhost:5000/receive_user_response',
method: "POST",
headers: {
"content-type": "application/json"
},
json: { // <--- I have also tried calling this as "body"
user_id: "some id...",
user_info: "some info..."
},
function(err, res, data) {
console.log('err', err) // <---- never prints any thing from here!
console.log('res', res)
console.log('data', data)
if (!err && res.statusCode == 200) {
console.log(data);
}
}
})
console.log("here...done..")
});

var server = app.listen(3000, function() {
console.log("Listening on port %s...", server.address().port);
});

最佳答案

回调函数必须是request函数的第二个参数。你不小心把它放在了 json 对象中。以下内容可行。

request({
url: 'http://localhost:5000/receive_user_response',
method: "POST",
headers: {
"content-type": "application/json"
},
json: { // <--- I have also tried calling this as "body"
user_id: "some id...",
user_info: "some info..."
}
},
function(err, res, data) {
console.log('err', err) // <---- never prints any thing from here!
console.log('res', res)
console.log('data', data)
if (!err && res.statusCode == 200) {
console.log(data);
}
}
)

但这绝对更适合阅读。

let options = {
url: 'http://localhost:5000/receive_user_response',
method: "POST",
headers: {
"content-type": "application/json"
},
json: { // <--- I have also tried calling this as "body"
user_id: "some id...",
user_info: "some info..."
}
};


request(options,
function(err, res, data) {
console.log('err', err) // <---- never prints any thing from here!
console.log('res', res)
console.log('data', data)
if (!err && res.statusCode == 200) {
console.log(data);
}
}
)

关于node.js - Node js request.post 回调未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41371152/

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