Using request https://github.com/request/request
function funcOne(input) {
var request = require('request');
request.post(someUrl, {json: true, body: input}, function(err, res, body) {
if (!err && res.statusCode === 200) {
funcTwo(body, function(err, output) {
console.log(err, output);
});
}
});
}
function funcTwo(input, callback) {
// process input
callback(null, input);
}
编辑:由于请求现已被弃用,您可以找到替代方案here https://github.com/request/request/issues/3143
您还可以使用最新版本的 nodejs(18+) 附带的内置 fetch API。请参阅下面的示例。
async function funcOne(input) {
try {
const response = await fetch(someUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(input),
});
if (response.ok) {
const body = await response.json();
funcTwo(body, (err, output) => {
console.log(err, output);
});
}
} catch (err) {
// Handle errors here
console.error(err);
}
}
function funcTwo(input, callback) {
// process input
callback(null, input);
}