javascript - Promise 解析时 JSON 输入意外结束

标签 javascript json http reactjs es6-promise

我正在从 openweather API 请求天气数据,每次我的 promise 得到解决并且我执行 JSON.pase(daat) 时,我都会收到“错误 SyntaxError: Unexpected end of JSON input at Object.parse ()” 我得到的 JSON 如下所示:

{
 "coord":{"lon":24.94,"lat":60.17},
 "weather":[{"id":741,"main":"Fog","description":"fog","icon":"50n"}],
 "base":"stations",
 "main":{"temp":273.15,"pressure":994,"humidity":94,"temp_min":273.15,"temp_max":273.15},
 "visibility":500,
 "wind":{"speed":1.5},
 "clouds":{"all":90},
 "dt":1489872000,
 "sys":{"type":1,"id":5019,"message":0.4444,"country":"FI","sunrise":1489811101,"sunset":1489854738},
 "id":658225,
 "name":"Helsinki",
 "cod":200
}

而且它似乎完全有效,至少从普通的 JS 文件请求它。 虽然来 self 的 React 应用程序(请参阅问题:) 我的代码如下所示:

httpRequestWeather(weatherNowHTTPQuery + "Helsinki" + weatherAPIToken).then(function(data){

    let myData = JSON.parse(data);
     //always returns error when trying to do JSON.parse()
    self.setState({
        weatherConditions: "Weather is here!"
     });
    self.setState({
        //always returns error when trying to do JSON.parse()
        weatherObj: JSON.parse(data)
    });

}).catch(function(err){
    console.log("error", err);
    self.setState({
        weatherConditions: "Buy"
     });

但是,在 http 请求内部,数据解析得非常好:

function httpRequestWeather(url) {
    return new Promise(function(resolve, reject) {
        var weatherRequest = new XMLHttpRequest();
        weatherRequest.open("GET", url, true);
        weatherRequest.onreadystatechange = function() {
            if ( this.status === 200) {
                console.log("request finished and response is ready");
                console.log(this.response);
                //this works perfectly fine

                self.setState({
                    weatherConditions: this.response
                 });
                resolve(this.response);
            } else{
                reject(new Error("no weather data"));
            }
          };
        weatherRequest.send();
    });
  }

最佳答案

您没有检查readyStatestatus 可以是 200 before readyState 为 4。请记住,您会收到多个回调到 onreadystatechange 处理程序,但 Promise 只能解析一次。

所以改变:

if ( this.status === 200) {
    // ...success...
} else {
    // ...error...
}

if ( this.readyState === 4 ) {
    if ( this.status === 200) {
        // ...success...
    } else {
        // ...error...
    }
}

这是您在 jsFiddle 上的原始内容(稍作修改以与 jsFiddle 的 JSON echo 内容一起使用),显示错误:https://jsfiddle.net/2n4to7go/

这是上面更新的一个,显示它正在工作:https://jsfiddle.net/2n4to7go/1/

关于javascript - Promise 解析时 JSON 输入意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42885936/

相关文章:

android - 解析 JSON,数组中的数组 (Android)

java - HTTP 状态 415 - 将数据从 ajax 作为 json 传递到 Restfull 服务器时出现不支持的媒体类型错误

java - Spring security - 自定义保持 Activity Controller

javascript - 选择并单击类中的链接

javascript - Angular 同位素 + 同位素不适用于我的网格

名称中带有方括号的 Javascript 对象

http - "q=0.9,*/*;q=0.8"是什么意思

javascript - 在脚本链接标签中使用注释

javascript - 原型(prototype)构造函数

http - Dart - 发送作为列表的 GET 参数