尝试调用webAPI时,我在Node.js中出现'Undefined:1'错误

时间:2017-08-04 21:05:19

标签: javascript node.js asp.net-web-api

我正在编写一些代码来阅读WebAPI。

C:\ Users \ XXXX \ XXXX \ XXXX> node 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和编码很新。但我尝试了其他三种试图让它发挥作用的方法。我没有想法

1 个答案:

答案 0 :(得分:0)

您可以尝试将以下内容添加到代码中以使其更加健壮和防错,检查响应代码,检查正文是否为空,将正文打印到日志以确保它是有效的JSON,如果API使用无效的JSON响应,则在try catch中解析正文。

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();