gpt4 book ai didi

node.js - 使用 Node.js 数据创建 POST http.request 的问题在 FormValue 而不是 Body 中传递

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:21:08 26 4
gpt4 key购买 nike

我尝试执行一个 http.request POST,我的数据被传递给 FormValue 而不是 Body。这是我在 Node.js http 调用中的第一个实验,所以如果问题微不足道,我深表歉意。我将调用传递给服务器,并在代码末尾获得了数据。

function doHttpApiCall(session,callback) {
var http = require('http');
var isEndedOk;
var outValue = '';
var postData = JSON.stringify({
grant_type: 'client_credentials',
scope: 'OOB',
my_id: 'my_id_value'
});



var postOptions = {
host: 'dummyapisite.com',
path: '/t/litf9-1571295453/post',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};

// Set up the request
var post_req = http.request(postOptions, function(res) {
var statusCode = res.statusCode;
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = rawData;
if (error) {
isEndedOk = false;
console.error(error.message);
console.error('Response Content=' + String(parsedData));
res.resume();
} else {
isEndedOk = true;
console.log('Response Content=' + String(parsedData));
}
callback(session.attributes,
callBack_doHttpApiCall(outValue, statusCode, session, callback, isEndedOk));
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
post_req.write(postData);
post_req.end();
}

这是服务器得到的结果,数据不在正确的地方。

{
"Timestamp":"2019-10-17T13:53:52.941575Z",
"Method":"POST",
"RemoteAddr":"34.245.148.80",
"ID":390940052,
"Headers":{
"Content-Length":[
"118"
],
"Content-Type":[
"application/x-www-form-urlencoded"
],
"Host":[
"ptsv2.com"
],
"X-Cloud-Trace-Context":[
"deff20a349bfb409fab118aa361ebc54/925376340939905763"
],
"X-Google-Apps-Metadata":[
"domain=gmail.com,host=dummyapisite.com"
]
},
"FormValues":{
"{\"body\":[{\"grant_type\":\"client_credentials\",\"scope\":\"OOB\",\"my_id\":\"my_id_value\"}]}":[
""
]
},
"Body":"",
"Files":null,
"MultipartValues":null
}

最佳答案

问题是您发送的是 JSON 正文,但是您发送的 Content-Type 是:application/x-www-form -urlencoded,所以改成application/json

您要发布到的服务器将值放入 FormValues 因为您告诉他们您正在发送表单 (x-www-form-urlencoded)

var postOptions = {
host: 'dummyapisite.com',
path: '/t/litf9-1571295453/post',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length
}
};

关于node.js - 使用 Node.js 数据创建 POST http.request 的问题在 FormValue 而不是 Body 中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434741/

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