NodeJS来自JSON调用的奇怪响应

问题描述:

我从我的JSON调用中得到了一个平滑的响应!这是我的响应输出: Console OutputNodeJS来自JSON调用的奇怪响应

这是我的JSON请求:

request({ 
url: url, 
json: true 
}, function (error, response, body) { 
    if (!error && response.statusCode === 200) { 
     console.log(body) 
    } 
}) 

我觉得这件事情错的字符集,但我不明白我怎么可以改变这一点。

解决方案:

// Had to decode url 
var encoded = encodeURIComponent(name); 
var url = "xxx" + encoded; 
+0

'的contentType: “应用程序/ JSON;字符集= UTF-8”,'介绍** **请求不响应。 – Quentin

+0

您需要分享您用于生成响应的代码。我们无法通过查看请求来判断它有什么问题。 – Quentin

+0

@Quentin这是我使用的一个示例url:http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=StatTrak%E2%84%A2%20UMP-45%20|%20Delusion%20(最小%20Wear) –

请求的charset我已经清除了很多误导性垃圾出的代码来解决问题的核心。

现在这地再现了原作的问题:

var request = require('request'); 

getItemPrice("StatTrak™ UMP-45 | Delusion (Minimal Wear)") 

function getItemPrice(market_hash_name, callback) { 
    var url = "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=" + market_hash_name; 

    request({ 
     url: url, 
     json: true 
    }, function(error, response, body) { 
     console.log(body); 
     if (!error && response.statusCode === 200) { 
      console.log(parseFloat(((body.lowest_price).replace(/\,/g, '.')).split('&')[0])); 
     } 
    }) 
} 

您的问题是什么,你在呼唤是不是一个有效的URL,服务器被严重反应的。

必须特殊字符编码成URL格式:

var url = "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=" + 
    encodeURIComponent(market_hash_name); 
+0

是的,我也同时找到了解决方案哈哈:)但非常感谢您的帮助 –

你叫什么样的REST API的?如果它的节点JS API,你可以设置的字符集有

var req = http.request(options, function(res) { 
    console.log('STATUS: ' + res.statusCode); 
    console.log('HEADERS: ' + JSON.stringify(res.headers)); 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
    console.log('BODY: ' + chunk); 
    }); 
}); 

如果不是的话,这样设置

request.setHeader('Accept-Charset', 'UTF-8)