从Chrome以外的浏览器进行访问时,解析提取的JSON数据时遇到问题。 Firefox返回最详细的错误:“ SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符”。在某些情况下,当代码托管在我的本地node.js开发环境中时,该代码将在其他浏览器中运行,但是当文件由SharePoint托管时,则仅在Chrome中运行。在我上传到github页面的示例中,它可以在Chrome中运行,而不能在Firefox中运行,等等。
function loadData() {
return fetch('./data.txt').then((response) => response.json());
}
function loadMoreData() {
return fetch('./moredata.txt').then((response) => response.json());
}
function loadAllData(){
return Promise.all([loadData(),loadMoreData()]);
}
loadAllData().then( ([data, moredata]) => {
console.log(data);
console.log(moredata);
});
data.txt:
[
{"emp_id":"90176","labor_code":"500"},
{"emp_id":"90202","labor_code":"500"},
{"emp_id":"90678","labor_code":"400"},
{"emp_id":"91245","labor_code":"300"},
{"emp_id":"91304","labor_code":"200"},
{"emp_id":"94377","labor_code":"100"},
{"emp_id":"94398","labor_code":"200"}
]
moredata.txt:
[
{"emp_id": "90176","hire_year": "1999"},
{"emp_id": "90202","hire_year": "2010"},
{"emp_id": "90678","hire_year": "2005"},
{"emp_id": "91245","hire_year": "1994"},
{"emp_id": "91304","hire_year": "1995"},
{"emp_id": "94377","hire_year": "1995"},
{"emp_id": "94398","hire_year": "1998"}
]
这是github数据的位置,在Chrome和Firefox上它可以正常工作,但是当我传输要由SharePoint托管的文件时,在Firefox中却没有:
演示(请参阅console.log):https://allenblair.github.io/fetchissue/
源文件:https://github.com/allenblair/fetchissue/
我的代码中是否有需要更改的内容?
答案 0 :(得分:0)
这是由于firefox中的获取导致返回未经授权的401
是的,谢谢@JLRishe
我们必须在标题中添加credentials: 'include'
我将它与SharePoint 2016中的react一起使用
componentDidMount() {
let headers = {
method: 'GET',
credentials: 'include',
headers: {
Accept: "application/json;odata=verbose"
},
mode: 'cors',
cache: 'default'
};
let siteURL = _spPageContextInfo.siteAbsoluteUrl;
let apiPath = siteURL + "/_api/web/lists/getbytitle('linksfooter')/items?$select=Title,LinkFooterColonne,LinkFooterContent,LinkFooterPosCol";
fetch(apiPath, headers)
.then(
res => res.json()
).then(
(d) => {
// console.log('fetched data = ', d)
let footerItemsResult = d.d.results;
let categories = footerItemsResult.map(item => item.LinkFooterColonne).filter(function (v, i, a) {
return a.indexOf(v) === i
})
// console.log('footerItemsResult = ', footerItemsResult)
this.setState({
isLoaded: true,
footerItems: footerItemsResult,
categories: categories
});
},
(error) => {
this.setState({
isLoaded: false,
error
});
}
)
}