问题描述
我正在尝试将正文数据添加到 Electron.js 的 post 请求中。但是数据写入其他一些属性。如何在请求中正确写入数据?
function tokenRequest() {
var postData = JSON.stringify({
username: USERNAME,password: PASSWORD,});
const tokenRequest = net.request({
method: 'POST',protocol: 'https:',hostname: HOST,port: PORT,path: '/api2/json/access/ticket',headers: {
'Content-Type': 'application/x-www-form-urlencoded',}
});
tokenRequest.on('response',(response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
response.on('data',(chunk) => {
console.log(`BODY: ${chunk}`);
});
response.on('end',() => {
console.log('No more data in tokenRequest response.');
});
});
tokenRequest.write(postData);
tokenRequest.end();
}
解决方法
由于 Proxmox 仅接受 URL 编码的 JSON 数据 (source),因此您必须将 JSON.stringify()
替换为 new URLSearchParams()
。还要在写入之前将 toString()
添加到 postData
。完整代码如下:
function tokenRequest() {
const postData = new URLSearchParams({ // <----
username: USERNAME,password: PASSWORD,})
const tokenRequest = net.request({
method: 'POST',protocol: 'https:',hostname: HOST,port: PORT,path: '/api2/json/access/ticket',headers: {
'Content-Type': 'application/x-www-form-urlencoded',},})
tokenRequest.on('response',(response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data',(chunk) => console.log(`BODY: ${chunk}`))
response.on('end',() => console.log('No more data in tokenRequest response.'))
})
tokenRequest.write(postData.toString()) // <----
tokenRequest.end()
}