Node.js nodejs请求post大型json失败
我试图将大型json发布到http服务器(实际上是grafana服务器): 这是我的密码:Node.js nodejs请求post大型json失败,node.js,http,Node.js,Http,我试图将大型json发布到http服务器(实际上是grafana服务器): 这是我的密码: const http = require('http') const request = require('request') const fs = require('fs') const opts = { hostname: 'myip', port: 3000, path: '/api/dashboards/uid/KPEiIQVWk', method: 'GET',
const http = require('http')
const request = require('request')
const fs = require('fs')
const opts = {
hostname: 'myip',
port: 3000,
path: '/api/dashboards/uid/KPEiIQVWk',
method: 'GET',
timeout: 5000,
headers : {
'Authorization' : 'Bearer ********************************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
}
const req = http.request(opts, res => {
console.log(`Fetch: statusCode: ${res.statusCode}`)
var origin = ''
res.on('data', d => {
origin += d
})
res.on('end', function(){
dash = JSON.parse(origin)
dash.dashboard.panels.forEach(p => {
if(p.id == 26){
fs.readFile(__dirname + '/grafana/pm/branch-graph.html','utf-8', function(err, newPanel){
if(err){
console.log(err)
}
p.content = newPanel
const fresh = JSON.stringify(dash)
const updateOptions = {
uri: 'http://myip:3000/api/dashboards/db',
method: 'post',
headers : {
'Authorization' : 'Bearer *************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Content-length' : fresh.length
},
json: fresh
}
fs.writeFile('tmp.json', fresh, function(err){
if(err){
console.error(err)
}
})
request(updateOptions, function(error, response, body){
console.log(`update: statusCode=${response.statusCode}`)
console.log(`update: ${body}`)
})
})
}
})
})
})
req.on('error', error => {
console.error(error)
})
req.on('timeout', () => {
req.abort()
})
req.end()
如您所见,我首先获取grafana仪表板的源代码,然后制作一些udpate,然后将其发布回grafana服务器。但总有400个错误。奇怪的是,如果我将json转储到一个文件中并使用curl进行post,它就会工作
curl -vH "Authorization: Bearer $TOKEN" -H "Expect:" -d @tmp.json -H "Content-Type:application/json" http://myip:3000/api/dashboards/db
整个json大约有40000多个字节。有什么提示吗?我不太熟悉nodejs。我只是想写一些CI脚本。首先,我认为没有必要同时使用
http
和请求
模块http
是内置在nodejs中的模块,request
是一个npm包
我建议您使用npm请求包,因为它更简单。您可以在此处阅读其文档:
其次,您传递给请求模块的选项格式不正确,我认为这就是它不起作用的原因。使用您当前的代码,我将console.log('POST error',error)
以打印出错误。下面提出了请求
模块的正确选项
const options = {
url: 'https://myip:3000/api/dashboards/db',
body: fresh, // the json from the fs.read callback
auth: {
'bearer': 'bearerToken'
},
json: true // from docs: If json is true, then body must be a JSON-serializable object.
}
request.post(
options,
(err, httpResponse, body) => {
console.log(err, body);
});
问题解决了,内容长度应该是
缓冲区。通过tellength(fresh,'utf-8')
,我犯了一个愚蠢的错误