![](/img/trans.png)
[英]Getting an undefined error when trying to set value of input node.js puppeteer
[英]I keep getting 'Undefined: 1' Error in Node.js when trying to call a webAPI
我目前正在編寫一些代碼來讀取WebAPI。
C:\\ Users \\ XXXX \\ XXXX \\ XXXX>節點bot.js未定義:1
SyntaxError:JSON輸入意外結束
at Object.parse (native)
at IncomingMessage.<anonymous> (C:\Users\XXXX\XXXX\XXXX\bot.js:82:20)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
這是我的代碼
var http = require('http');
var options = {
host: 'backpack.tf',
port: 80,
path: '/api/IGetPrices/v4?key="personalapikey"',
method: 'GET'
};
http.request(options, function(res){
var body = '';
res.on('data', function(chunk){
body+=chunk;
});
res.on('end', function(){
var price = JSON.parse(body);
console.log(price);
});
}).end();
我對node.js和一般編碼非常陌生。 但是我嘗試了其他3種方法來使其正常工作。 我沒主意了
您可以嘗試將以下內容添加到代碼中,以使其更健壯和更防出錯,檢查響應代碼,檢查正文是否為空,將正文打印到日志中以確保它是有效的JSON,然后解析如果API使用無效的JSON響應,則嘗試捕獲正文。
var http = require('http');
var options = {
host: 'backpack.tf',
port: 80,
path: '/api/IGetPrices/v4?key="personalapikey"',
method: 'GET'
};
http.request(options, function(res){
var body = '';
res.on('data', function(chunk){
body+=chunk;
});
res.on('end', function(){
if (res.statusCode == 200) { // Check the status code returned in the response
try { // Add try catch block to handle corrupted json in response
if (body != '') { // Check that the body isn't empty
console.log(body); // Print the body to check if it's actually a valid JSON
var price = JSON.parse(body);
console.log(price);
} else {
console.log('Body is empty');
}
} catch (err) {
console.log(err);
}
} else {
console.log('Status code: ' + res.statusCode);
}
});
}).end();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.