简体   繁体   English

NodeJS来自JSON调用的奇怪响应

[英]NodeJS Strange response from JSON call

I got a strage response from my JSON call! 我收到了JSON电话的响应! This is my response output: Console Output 这是我的响应输出: 控制台输出

And that's my JSON request: 那是我的JSON请求:

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

I think it's something wrong about the charset, but i don't get how i can change this. 我认为这是charset的错误,但我不知道如何改变它。

Solution: 解:

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

I've cleared a lot of misleading junk out of your code to get to the heart of the problem. 我已经从你的代码中清除了很多误导性的垃圾,以解决问题的核心。

This now reproduces the original issue: 现在重现原始问题:

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]));
        }
    })
}

Your problem is that what you are calling is not a valid URL and the server is reacting to it badly. 您的问题是您所呼叫的内容不是有效的URL,服务器对此做出了严重的反应。

You must encode special characters into the URL format: 您必须将特殊字符编码为URL格式:

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

What kind of REST API do you call? 你叫什么样的REST API? If it's node js API, you can set the charset there 如果是节点js API,则可以在那里设置charset

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

And if that is not the case, set the request charset like this 如果不是这种情况,请像这样设置请求字符集

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM