我从developers.themoviedb.org得到了这个对象,但是真的让一些错误失望了
该对象被发送到浏览器,但我不明白如何把它扔给我
我很困惑,需要帮助
如果在中间件中我写了let arr = JSON.parse(response).results;
也是一个错误:
Unexpected token o in JSON at position 1
response with object in browser
data.service.js
export const getData = (url) => new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', url);
request.onload = () =>
(request.status === 200) ?
resolve(JSON.parse(request.response).results) :
reject(Error(request.statusText))
request.onerror = (err) => reject(err)
request.send();
});
movies.middleware.js
export const moviesMiddleware = store => next => action => {
if (action.type === FETCH_MOVIES_START) {
getData(popularMovies).then((response) => {
let arr = response.results;
let movies = arr.map((item) => {
return new MovieEntity(item);
});
let data = movies;
store.dispatch({
type: FETCH_MOVIES_SUCCESS,
payload: data
});
});
}
return next(action);
}
movies.action.js
export function fetchMovies() {
return {
type: FETCH_MOVIES_START
}
}
答案 0 :(得分:1)
您的数据已经是一个对象。无需解析它。并且每次解析之前检查typeOf param是否为字符串。 ------ ----- EDIT
同时尝试:
resolve(
if(typeOf(request.response)=='string')
JSON.parse(request.response).results
else request.response.results
)
在movies.middleware.js中的更改如下
export const moviesMiddleware = store => next => action => {
if (action.type === FETCH_MOVIES_START) {
getData(popularMovies).then((response) => {
let arr = response;
let movies = arr.map((item) => {
return new MovieEntity(item);
});
let data = movies;
store.dispatch({
type: FETCH_MOVIES_SUCCESS,
payload: data
});
});
}
return next(action);
}
问题在于您正在使用request.response.results解决承诺,然后您再次以相同的方式访问它.response返回request.response或更改访问权限响应。< / p>